toshiki-notebook https://note.toshiki.dev/ Toshiki's web notebook served via Vitepress! Sat, 14 Sep 2024 11:06:25 GMT https://validator.w3.org/feed/docs/rss2.html https://github.com/jpmonette/feed en-US toshiki-notebook https://note.toshiki.dev/logo-308px.png https://note.toshiki.dev/ Copyright (c) 2023-present, Anda Toshiki at Toshiki Dev <![CDATA[Welcome to Chemistry ]]> https://note.toshiki.dev/academic/chemistry/ https://note.toshiki.dev/academic/chemistry/ Thu, 01 Jul 2021 00:00:00 GMT Welcome to Chemistry ]]> Welcome to Chemistry ]]> <![CDATA[12-5: Reaction Mechanism]]> https://note.toshiki.dev/academic/chemistry/notes/12-5 https://note.toshiki.dev/academic/chemistry/notes/12-5 Thu, 01 Jul 2021 00:00:00 GMT 12-5: Reaction Mechanism

12-5-1: Learning Objectives

Learning Objectives

One of the major reasons for studying chemical kinetics is to use measurements of the macroscopic properties of a system, such as the rate of change in the concentration of reactants or products with time, to discover the sequence of events that occur at the molecular level during a reaction. This molecular description is the mechanism of the reaction; it describes how individual atoms, ions, or molecules interact to form particular products. The stepwise changes are collectively called the reaction mechanism.

In an internal combustion engine, for example, isooctane reacts with oxygen to give carbon dioxide and water:

2C8H18(l)+25O2( g)16CO2( g)+18H2O(g)2 \mathrm{C}_{8} \mathrm{H}_{18}(\mathrm{l})+25 \mathrm{O}_{2}(\mathrm{~g}) \longrightarrow 16 \mathrm{CO}_{2}(\mathrm{~g})+18 \mathrm{H}_{2} \mathrm{O}(\mathrm{g})

For this reaction to occur in a single step, 25 dioxygen molecules and 2 isooctane molecules would have to collide simultaneously and be converted to 34 molecules of product, which is very unlikely. It is more likely that a complex series of reactions takes place in a stepwise fashion. Each individual reaction, which is called an elementary reaction, involves one, two, or (rarely) three atoms, molecules, or ions. The overall sequence of elementary reactions is the mechanism of the reaction. The sum of the individual steps, or elementary reactions, in the mechanism must give the balanced chemical equation for the overall reaction.

The overall sequence of elementary reactions is the mechanism of the reaction.

12-5-2: Molecularity and the Rate-Determining Step

To demonstrate how the analysis of elementary reactions helps us determine the overall reaction mechanism, we will examine the much simpler reaction of carbon monoxide with nitrogen dioxide.

2CO+2NO22CO2+N2O4\mathrm{2CO + 2NO_2 \rightarrow 2CO_2 + N_2O_4}

From the balanced chemical equation, one might expect the reaction to occur via a collision of one molecule of NO2\mathrm{NO}_{2} with a molecule of CO\mathrm{CO} that results in the transfer of an oxygen atom from nitrogen to carbon. The experimentally determined rate law for the reaction, however, is as follows:

 rate =k[NO2]2\text { rate }=k\left[\mathrm{NO}_{2}\right]^{2}

The fact that the reaction is second order in [NO2]\left[\mathrm{NO}_{2}\right] and independent of [CO][\mathrm{CO}] tells us that it does not occur by the simple collision model outlined previously. If it did, its predicted rate law would be

 rate =k[NO2][CO].\text { rate }=k\left[\mathrm{NO}_{2}\right][\mathrm{CO}] .

The following two-step mechanism is consistent with the rate law if step 1 is much slower than step 2:

15-2-1: Two-Step Mechanism

Steps Reaction Reaction Type
step 1 NO2+NO2 slow NO3+NO\mathrm{NO}_{2}+\mathrm{NO}_{2} \stackrel{\text { slow }}{\longrightarrow} \mathrm{NO}_{3}+\mathrm{NO} elementary reaction
step 2 NO3+CONO2+CO2\underline{\mathrm{NO}_{3}+\mathrm{CO} \rightarrow \mathrm{NO}_{2}+\mathrm{CO}_{2}} elementary reaction
sum NO2+CONO+CO2\mathrm{NO}_{2}+\mathrm{CO} \rightarrow \mathrm{NO}+\mathrm{CO}_{2} overall reaction

According to this mechanism, the overall reaction occurs in two steps, or elementary reactions. Summing steps 1 and 2 and canceling on both sides of the equation gives the overall balanced chemical equation for the reaction. The NO3\mathrm{NO_3} molecule is intermediate in the reaction, a species that does not appear in the balanced chemical equation for the overall reaction. It is formed as a product of the first step but is consumed in the second step.

The sum of the elementary reactions in a reaction mechanism must give the overall balanced chemical equation of the reaction.

12-5-3: Using Molecularity to Describe a Rate Law

The molecularity of an elementary reaction is the number of molecules that collide during that step in the mechanism. If there is only a single reactant molecule in an elementary reaction, that step is designated as unimolecular; if there are two reactant molecules, it is bimolecular; and if there are three reactant molecules (a relatively rare situation), it is termolecular. Elementary reactions that involve the simultaneous collision of more than three molecules are highly improbable and have never been observed experimentally. (To understand why, try to make three or more marbles or pool balls collide with one another simultaneously!)

About the image

The Basis for Writing Rate Laws of Elementary Reactions. This diagram illustrates how the number of possible collisions per unit time between two reactant species, A and B, depends on the number of A and B particles present. The number of collisions between A and B particles increases as the product of the number of particles, not as the sum. This is why the rate law for an elementary reaction depends on the product of the concentrations of the species that collide in that step. (CC BY-NC-SA; anonymous)

Writing the rate law for an elementary reaction is straightforward because we know how many molecules must collide simultaneously for the elementary reaction to occur; hence the order of the elementary reaction is the same as its molecularity (Table 14.6.1). In contrast, the rate law for the reaction cannot be determined from the balanced chemical equation for the overall reaction. The general rate law for a unimolecular elementary reaction ( A\mathrm{A} \rightarrow products) is

 rate =k[A].\text { rate }=k[A] .

For bimolecular reactions, the reaction rate depends on the number of collisions per unit time, which is proportional to the product of the concentrations of the reactants, as shown in Figure 14.6.1 For a bimolecular elementary reaction of the form A+B\mathrm{A}+\mathrm{B} \rightarrow products, the general rate law is

 rate =k[A][B].\text { rate }=k[A][B] .

Elementary Reaction Molecularity Rate Reaction Order
A products \mathrm{A} \rightarrow \text { products } Unimolecular  rate =k[ A]\text { rate }=k[\mathrm{~A}] first
2 A products 2\mathrm{~A} \rightarrow \text { products } Bimolecular  rate =k[ A]2\text { rate }=k[\mathrm{~A}]^2 second
A+B products \mathrm{A}+\mathrm{B} \rightarrow \text { products } Bimolecular  rate =k[ A][B]\text { rate }=k[\mathrm{~A}][\mathrm{B}] second
2 A+B products 2 \mathrm{~A}+\mathrm{B} \rightarrow \text { products } Termolecular  rate =k[ A]2[ B]\text { rate }=k[\mathrm{~A}]^2[\mathrm{~B}] third
A+B+C products \mathrm{A}+\mathrm{B}+\mathrm{C} \rightarrow \text { products } Termolecular  rate =k[ A][B][C]\text { rate }=k[\mathrm{~A}][\mathrm{B}][\mathrm{C}] third

For elementary reactions, the order of the elementary reaction is the same as its molecularity. In contrast, the rate law cannot be determined from the balanced chemical equation for the overall reaction (unless it is a single step mechanism and is therefore also an elementary step).

12-5-4: Identifying the Rate-Determining Step

Note the important difference between writing rate laws for elementary reactions and the balanced chemical equation of the overall reaction. Because the balanced chemical equation does not necessarily reveal the individual elementary reactions by which the reaction occurs, we cannot obtain the rate law for a reaction from the overall balanced chemical equation alone. In fact, it is the rate law for the slowest overall reaction, which is the same as the rate law for the slowest step in the reaction mechanism, the ratedetermining step, that must give the experimentally determined rate law for the overall reaction.This statement is true if one step is substantially slower than all the others, typically by a factor of 10 or more. If two or more slow steps have comparable rates, the experimentally determined rate laws can become complex. Our discussion is limited to reactions in which one step can be identified as being substantially slower than any other. The reason for this is that any process that occurs through a sequence of steps can take place no faster than the slowest step in the sequence. In an automotive assembly line, for example, a component cannot be used faster than it is produced. Similarly, blood pressure is regulated by the flow of blood through the smallest passages, the capillaries. Because movement through capillaries constitutes the rate-determining step in blood flow, blood pressure can be regulated by medications that cause the capillaries to contract or dilate. A chemical reaction that occurs via a series of elementary reactions can take place no faster than the slowest step in the series of reactions.

Look at the rate laws for each elementary reaction in the example as well as for the overall reaction.

Rate laws for each elementary reaction in our example as well as for the overall reaction

Steps Reaction Rate
step 1 NO2+NO2k1NO3+NO\mathrm{NO}_2+\mathrm{NO}_2 \stackrel{\mathrm{k}_1}{\rightarrow} \mathrm{NO}_3+\mathrm{NO}  rate =k1[NO2]2( predicted) \text { rate }=k_1\left[\mathrm{NO}_2\right]^2(\text { predicted) }
step 2 NO3+COk2NO2+CO2\underline{\mathrm{NO}_3+\mathrm{CO} \stackrel{k_2}{\rightarrow} \mathrm{NO}_2+\mathrm{CO}_2}  rate =k2[NO3][CO]( predicted )\text { rate }=k_2\left[\mathrm{NO}_3\right][\mathrm{CO}](\text { predicted })
step 3 NO2+COkNO+CO2\mathrm{NO}_2+\mathrm{CO} \stackrel{k}{\rightarrow} \mathrm{NO}+\mathrm{CO}_2  rate =k[NO2]2( observed) \text { rate }=k\left[\mathrm{NO}_2\right]^2(\text { observed) }

The experimentally determined rate law for the reaction of NO2\mathrm{NO}_{2} with COC O is the same as the predicted rate law for step 1 . This tells us that the first elementary reaction is the rate-determining step, so kk for the overall reaction must equal k1k_{1}. That is, NO3\mathrm{NO}_{3} is formed slowly in step 1, but once it is formed, it reacts very rapidly with CO in step 2.

Sometimes chemists are able to propose two or more mechanisms that are consistent with the available data. If a proposed mechanism predicts the wrong experimental rate law, however, the mechanism must be incorrect.

12-5-4-1: Example-A Reaction with an Intermediate

In an alternative mechanism for the reaction of NO2\mathrm{NO}_{2} with CO\mathrm{CO} with N2O4\mathrm{N}_{2} \mathrm{O}_{4} appearing as an intermediate.

alternative mechanism for the reaction of NO2\mathrm{NO}_{2} with CO\mathrm{CO} with N2O4\mathrm{N}_{2} \mathrm{O}_{4} appearing as an intermediate.

Write the rate law for each elementary reaction. Is this mechanism consistent with the experimentally determined rate law (rate =k[NO2]2t=\mathrm{k[{NO}_{2}]^{2}t})

Given: elementary reactions Asked for: rate law for each elementary reaction and overall rate law

Strategy

  • Determine the rate law for each elementary reaction in the reaction.

  • Determine which rate law corresponds to the experimentally determined rate law for the reaction. This rate law is the one for the rate-determining step.

Solution

View solution

A The rate law for step 1 is rate =k1[NO2]2=k_{1}\left[\mathrm{NO}_{2}\right]^{2}; for step 2 , it is rate =k2[ N2O4][CO]=k_{2}\left[\mathrm{~N}_{2} \mathrm{O}_{4}\right][\mathrm{CO}].

B If step 1 is slow (and therefore the rate-determining step), then the overall rate law for the reaction will be the same: rate == k1[NO2]2k_{1}\left[\mathrm{NO}_{2}\right]^{2}. This is the same as the experimentally determined rate law. Hence this mechanism, with N2O4\mathrm{N}_{2} \mathrm{O}_{4} as an intermediate, and the one described previously, with NO3\mathrm{NO}_{3} as an intermediate, are kinetically indistinguishable. In this case, further experiments are needed to distinguish between them. For example, the researcher could try to detect the proposed intermediates, NO3\mathrm{NO}_{3} and N2O4\mathrm{N}_{2} \mathrm{O}_{4}, directly.

]]>
12-5: Reaction Mechanism

12-5-1: Learning Objectives

Learning Objectives

One of the major reasons for studying chemical kinetics is to use measurements of the macroscopic properties of a system, such as the rate of change in the concentration of reactants or products with time, to discover the sequence of events that occur at the molecular level during a reaction. This molecular description is the mechanism of the reaction; it describes how individual atoms, ions, or molecules interact to form particular products. The stepwise changes are collectively called the reaction mechanism.

In an internal combustion engine, for example, isooctane reacts with oxygen to give carbon dioxide and water:

2C8H18(l)+25O2( g)16CO2( g)+18H2O(g)2 \mathrm{C}_{8} \mathrm{H}_{18}(\mathrm{l})+25 \mathrm{O}_{2}(\mathrm{~g}) \longrightarrow 16 \mathrm{CO}_{2}(\mathrm{~g})+18 \mathrm{H}_{2} \mathrm{O}(\mathrm{g})

For this reaction to occur in a single step, 25 dioxygen molecules and 2 isooctane molecules would have to collide simultaneously and be converted to 34 molecules of product, which is very unlikely. It is more likely that a complex series of reactions takes place in a stepwise fashion. Each individual reaction, which is called an elementary reaction, involves one, two, or (rarely) three atoms, molecules, or ions. The overall sequence of elementary reactions is the mechanism of the reaction. The sum of the individual steps, or elementary reactions, in the mechanism must give the balanced chemical equation for the overall reaction.

The overall sequence of elementary reactions is the mechanism of the reaction.

12-5-2: Molecularity and the Rate-Determining Step

To demonstrate how the analysis of elementary reactions helps us determine the overall reaction mechanism, we will examine the much simpler reaction of carbon monoxide with nitrogen dioxide.

2CO+2NO22CO2+N2O4\mathrm{2CO + 2NO_2 \rightarrow 2CO_2 + N_2O_4}

From the balanced chemical equation, one might expect the reaction to occur via a collision of one molecule of NO2\mathrm{NO}_{2} with a molecule of CO\mathrm{CO} that results in the transfer of an oxygen atom from nitrogen to carbon. The experimentally determined rate law for the reaction, however, is as follows:

 rate =k[NO2]2\text { rate }=k\left[\mathrm{NO}_{2}\right]^{2}

The fact that the reaction is second order in [NO2]\left[\mathrm{NO}_{2}\right] and independent of [CO][\mathrm{CO}] tells us that it does not occur by the simple collision model outlined previously. If it did, its predicted rate law would be

 rate =k[NO2][CO].\text { rate }=k\left[\mathrm{NO}_{2}\right][\mathrm{CO}] .

The following two-step mechanism is consistent with the rate law if step 1 is much slower than step 2:

15-2-1: Two-Step Mechanism

Steps Reaction Reaction Type
step 1 NO2+NO2 slow NO3+NO\mathrm{NO}_{2}+\mathrm{NO}_{2} \stackrel{\text { slow }}{\longrightarrow} \mathrm{NO}_{3}+\mathrm{NO} elementary reaction
step 2 NO3+CONO2+CO2\underline{\mathrm{NO}_{3}+\mathrm{CO} \rightarrow \mathrm{NO}_{2}+\mathrm{CO}_{2}} elementary reaction
sum NO2+CONO+CO2\mathrm{NO}_{2}+\mathrm{CO} \rightarrow \mathrm{NO}+\mathrm{CO}_{2} overall reaction

According to this mechanism, the overall reaction occurs in two steps, or elementary reactions. Summing steps 1 and 2 and canceling on both sides of the equation gives the overall balanced chemical equation for the reaction. The NO3\mathrm{NO_3} molecule is intermediate in the reaction, a species that does not appear in the balanced chemical equation for the overall reaction. It is formed as a product of the first step but is consumed in the second step.

The sum of the elementary reactions in a reaction mechanism must give the overall balanced chemical equation of the reaction.

12-5-3: Using Molecularity to Describe a Rate Law

The molecularity of an elementary reaction is the number of molecules that collide during that step in the mechanism. If there is only a single reactant molecule in an elementary reaction, that step is designated as unimolecular; if there are two reactant molecules, it is bimolecular; and if there are three reactant molecules (a relatively rare situation), it is termolecular. Elementary reactions that involve the simultaneous collision of more than three molecules are highly improbable and have never been observed experimentally. (To understand why, try to make three or more marbles or pool balls collide with one another simultaneously!)

About the image

The Basis for Writing Rate Laws of Elementary Reactions. This diagram illustrates how the number of possible collisions per unit time between two reactant species, A and B, depends on the number of A and B particles present. The number of collisions between A and B particles increases as the product of the number of particles, not as the sum. This is why the rate law for an elementary reaction depends on the product of the concentrations of the species that collide in that step. (CC BY-NC-SA; anonymous)

Writing the rate law for an elementary reaction is straightforward because we know how many molecules must collide simultaneously for the elementary reaction to occur; hence the order of the elementary reaction is the same as its molecularity (Table 14.6.1). In contrast, the rate law for the reaction cannot be determined from the balanced chemical equation for the overall reaction. The general rate law for a unimolecular elementary reaction ( A\mathrm{A} \rightarrow products) is

 rate =k[A].\text { rate }=k[A] .

For bimolecular reactions, the reaction rate depends on the number of collisions per unit time, which is proportional to the product of the concentrations of the reactants, as shown in Figure 14.6.1 For a bimolecular elementary reaction of the form A+B\mathrm{A}+\mathrm{B} \rightarrow products, the general rate law is

 rate =k[A][B].\text { rate }=k[A][B] .

Elementary Reaction Molecularity Rate Reaction Order
A products \mathrm{A} \rightarrow \text { products } Unimolecular  rate =k[ A]\text { rate }=k[\mathrm{~A}] first
2 A products 2\mathrm{~A} \rightarrow \text { products } Bimolecular  rate =k[ A]2\text { rate }=k[\mathrm{~A}]^2 second
A+B products \mathrm{A}+\mathrm{B} \rightarrow \text { products } Bimolecular  rate =k[ A][B]\text { rate }=k[\mathrm{~A}][\mathrm{B}] second
2 A+B products 2 \mathrm{~A}+\mathrm{B} \rightarrow \text { products } Termolecular  rate =k[ A]2[ B]\text { rate }=k[\mathrm{~A}]^2[\mathrm{~B}] third
A+B+C products \mathrm{A}+\mathrm{B}+\mathrm{C} \rightarrow \text { products } Termolecular  rate =k[ A][B][C]\text { rate }=k[\mathrm{~A}][\mathrm{B}][\mathrm{C}] third

For elementary reactions, the order of the elementary reaction is the same as its molecularity. In contrast, the rate law cannot be determined from the balanced chemical equation for the overall reaction (unless it is a single step mechanism and is therefore also an elementary step).

12-5-4: Identifying the Rate-Determining Step

Note the important difference between writing rate laws for elementary reactions and the balanced chemical equation of the overall reaction. Because the balanced chemical equation does not necessarily reveal the individual elementary reactions by which the reaction occurs, we cannot obtain the rate law for a reaction from the overall balanced chemical equation alone. In fact, it is the rate law for the slowest overall reaction, which is the same as the rate law for the slowest step in the reaction mechanism, the ratedetermining step, that must give the experimentally determined rate law for the overall reaction.This statement is true if one step is substantially slower than all the others, typically by a factor of 10 or more. If two or more slow steps have comparable rates, the experimentally determined rate laws can become complex. Our discussion is limited to reactions in which one step can be identified as being substantially slower than any other. The reason for this is that any process that occurs through a sequence of steps can take place no faster than the slowest step in the sequence. In an automotive assembly line, for example, a component cannot be used faster than it is produced. Similarly, blood pressure is regulated by the flow of blood through the smallest passages, the capillaries. Because movement through capillaries constitutes the rate-determining step in blood flow, blood pressure can be regulated by medications that cause the capillaries to contract or dilate. A chemical reaction that occurs via a series of elementary reactions can take place no faster than the slowest step in the series of reactions.

Look at the rate laws for each elementary reaction in the example as well as for the overall reaction.

Rate laws for each elementary reaction in our example as well as for the overall reaction

Steps Reaction Rate
step 1 NO2+NO2k1NO3+NO\mathrm{NO}_2+\mathrm{NO}_2 \stackrel{\mathrm{k}_1}{\rightarrow} \mathrm{NO}_3+\mathrm{NO}  rate =k1[NO2]2( predicted) \text { rate }=k_1\left[\mathrm{NO}_2\right]^2(\text { predicted) }
step 2 NO3+COk2NO2+CO2\underline{\mathrm{NO}_3+\mathrm{CO} \stackrel{k_2}{\rightarrow} \mathrm{NO}_2+\mathrm{CO}_2}  rate =k2[NO3][CO]( predicted )\text { rate }=k_2\left[\mathrm{NO}_3\right][\mathrm{CO}](\text { predicted })
step 3 NO2+COkNO+CO2\mathrm{NO}_2+\mathrm{CO} \stackrel{k}{\rightarrow} \mathrm{NO}+\mathrm{CO}_2  rate =k[NO2]2( observed) \text { rate }=k\left[\mathrm{NO}_2\right]^2(\text { observed) }

The experimentally determined rate law for the reaction of NO2\mathrm{NO}_{2} with COC O is the same as the predicted rate law for step 1 . This tells us that the first elementary reaction is the rate-determining step, so kk for the overall reaction must equal k1k_{1}. That is, NO3\mathrm{NO}_{3} is formed slowly in step 1, but once it is formed, it reacts very rapidly with CO in step 2.

Sometimes chemists are able to propose two or more mechanisms that are consistent with the available data. If a proposed mechanism predicts the wrong experimental rate law, however, the mechanism must be incorrect.

12-5-4-1: Example-A Reaction with an Intermediate

In an alternative mechanism for the reaction of NO2\mathrm{NO}_{2} with CO\mathrm{CO} with N2O4\mathrm{N}_{2} \mathrm{O}_{4} appearing as an intermediate.

alternative mechanism for the reaction of NO2\mathrm{NO}_{2} with CO\mathrm{CO} with N2O4\mathrm{N}_{2} \mathrm{O}_{4} appearing as an intermediate.

Write the rate law for each elementary reaction. Is this mechanism consistent with the experimentally determined rate law (rate =k[NO2]2t=\mathrm{k[{NO}_{2}]^{2}t})

Given: elementary reactions Asked for: rate law for each elementary reaction and overall rate law

Strategy

  • Determine the rate law for each elementary reaction in the reaction.

  • Determine which rate law corresponds to the experimentally determined rate law for the reaction. This rate law is the one for the rate-determining step.

Solution

View solution

A The rate law for step 1 is rate =k1[NO2]2=k_{1}\left[\mathrm{NO}_{2}\right]^{2}; for step 2 , it is rate =k2[ N2O4][CO]=k_{2}\left[\mathrm{~N}_{2} \mathrm{O}_{4}\right][\mathrm{CO}].

B If step 1 is slow (and therefore the rate-determining step), then the overall rate law for the reaction will be the same: rate == k1[NO2]2k_{1}\left[\mathrm{NO}_{2}\right]^{2}. This is the same as the experimentally determined rate law. Hence this mechanism, with N2O4\mathrm{N}_{2} \mathrm{O}_{4} as an intermediate, and the one described previously, with NO3\mathrm{NO}_{3} as an intermediate, are kinetically indistinguishable. In this case, further experiments are needed to distinguish between them. For example, the researcher could try to detect the proposed intermediates, NO3\mathrm{NO}_{3} and N2O4\mathrm{N}_{2} \mathrm{O}_{4}, directly.

]]>
<![CDATA[Presentation problem: 02-20 ]]> https://note.toshiki.dev/academic/chemistry/problems/02-20 https://note.toshiki.dev/academic/chemistry/problems/02-20 Thu, 01 Jul 2021 00:00:00 GMT Presentation problem: 02-20

Question

At 500 K500 \mathrm{~K} in the presence of a copper surface, ethanol decomposes according to the equation

C2H5OH(g)CH3CHO(g)+H2(g)\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH}(\mathrm{g}) \longrightarrow \mathrm{CH}_3 \mathrm{CHO}(g)+\mathrm{H}_2(g)

The pressure of C2H5OH\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH} was measured as a function of time and the following data were obtained:

Time (s) PC2H5OH (torr) P_{\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH}} \text { (torr) }
0 250.
100. 237
200. 224
300. 211
400. 198
500. 185

Since the pressure of a gas is directly proportional to the concentration of gas, we can express the rate law for a gaseous reaction in terms of partial pressures. Using the above data, deduce the rate law, the integrated rate law, and the value of the rate constant, all in terms of pressure units in atm and time in seconds. Predict the pressure of C2H5OH\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH} after 900.s900 . \mathrm{s} from the start of the reaction. (Hint: To determine the order of the reaction with respect to C2H5OH\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH}, compare how the pressure of C2H5OH\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH} decreases with each time listing.)

Solution

solution graph

Due to the fact that the graph of p[O2]\mathrm{p}\left[\mathrm{O}_2\right] over time is showing R2\mathrm{R}^2 value of 1 we know we have a zero-order reaction. Therefore:

k=p0[C2H5OH]p[C2H5OH]t=250 torr 185 torr 500 s=0.13 torr s 1k=0.13 torr s s1×1 atm760 torr =1.71×104 atm s1 rate =kp(C2H5OH)=kt+p0(C2H5OH)p(C2H5OH)=(1.71×104 atm s1)×900 s+0.33 atmp(C2H5OH)=0.176 atm s1\begin{aligned} & \mathrm{k}=\frac{\mathrm{p}_0\left[\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH}\right]-\mathrm{p}\left[\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH}\right]}{\mathrm{t}}=\frac{250 \text { torr }-185 \text { torr }}{500 \mathrm{~s}}=0.13 \text { torr s }^{-1} \\ & \mathrm{k}=0.13 \text { torr s } \mathrm{s}^{-1} \times \frac{1 \mathrm{~atm}}{760 \text { torr }}=1.71 \times 10^{-4} \mathrm{~atm} \mathrm{~s}^{-1} \\ & \text { rate }=\mathbf{k} \\ & \mathrm{p}\left(\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH}\right)=-\mathrm{kt}+\mathrm{p}_0\left(\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH}\right) \\ & \mathrm{p}\left(\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH}\right)=-\left(1.71 \times 10^{-4} \mathrm{~atm} \mathrm{~s}^{-1}\right) \times 900 \mathrm{~s}+0.33 \mathrm{~atm} \\ & \mathrm{p}\left(\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH}\right)=0.176 \mathrm{~atm} \mathrm{~s}^{-1} \\ & \end{aligned}

]]>
Presentation problem: 02-20

Question

At 500 K500 \mathrm{~K} in the presence of a copper surface, ethanol decomposes according to the equation

C2H5OH(g)CH3CHO(g)+H2(g)\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH}(\mathrm{g}) \longrightarrow \mathrm{CH}_3 \mathrm{CHO}(g)+\mathrm{H}_2(g)

The pressure of C2H5OH\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH} was measured as a function of time and the following data were obtained:

Time (s) PC2H5OH (torr) P_{\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH}} \text { (torr) }
0 250.
100. 237
200. 224
300. 211
400. 198
500. 185

Since the pressure of a gas is directly proportional to the concentration of gas, we can express the rate law for a gaseous reaction in terms of partial pressures. Using the above data, deduce the rate law, the integrated rate law, and the value of the rate constant, all in terms of pressure units in atm and time in seconds. Predict the pressure of C2H5OH\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH} after 900.s900 . \mathrm{s} from the start of the reaction. (Hint: To determine the order of the reaction with respect to C2H5OH\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH}, compare how the pressure of C2H5OH\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH} decreases with each time listing.)

Solution

solution graph

Due to the fact that the graph of p[O2]\mathrm{p}\left[\mathrm{O}_2\right] over time is showing R2\mathrm{R}^2 value of 1 we know we have a zero-order reaction. Therefore:

k=p0[C2H5OH]p[C2H5OH]t=250 torr 185 torr 500 s=0.13 torr s 1k=0.13 torr s s1×1 atm760 torr =1.71×104 atm s1 rate =kp(C2H5OH)=kt+p0(C2H5OH)p(C2H5OH)=(1.71×104 atm s1)×900 s+0.33 atmp(C2H5OH)=0.176 atm s1\begin{aligned} & \mathrm{k}=\frac{\mathrm{p}_0\left[\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH}\right]-\mathrm{p}\left[\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH}\right]}{\mathrm{t}}=\frac{250 \text { torr }-185 \text { torr }}{500 \mathrm{~s}}=0.13 \text { torr s }^{-1} \\ & \mathrm{k}=0.13 \text { torr s } \mathrm{s}^{-1} \times \frac{1 \mathrm{~atm}}{760 \text { torr }}=1.71 \times 10^{-4} \mathrm{~atm} \mathrm{~s}^{-1} \\ & \text { rate }=\mathbf{k} \\ & \mathrm{p}\left(\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH}\right)=-\mathrm{kt}+\mathrm{p}_0\left(\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH}\right) \\ & \mathrm{p}\left(\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH}\right)=-\left(1.71 \times 10^{-4} \mathrm{~atm} \mathrm{~s}^{-1}\right) \times 900 \mathrm{~s}+0.33 \mathrm{~atm} \\ & \mathrm{p}\left(\mathrm{C}_2 \mathrm{H}_5 \mathrm{OH}\right)=0.176 \mathrm{~atm} \mathrm{~s}^{-1} \\ & \end{aligned}

]]>
<![CDATA[Problem: 03-02-1 ]]> https://note.toshiki.dev/academic/chemistry/problems/03-02-1 https://note.toshiki.dev/academic/chemistry/problems/03-02-1 Thu, 01 Jul 2021 00:00:00 GMT Problem: 03-02-1

Question

2 N2O5(g)4NO2(g)+O2(g)2 \mathrm{~N}_2 \mathrm{O}_5(g) \rightarrow 4 \mathrm{NO}_2(g)+\mathrm{O}_2(g)

The decomposition of N2O5(g)\mathrm{N}_2 \mathrm{O}_5(g) is represented by the equation above. A sample of N2O5(g)\mathrm{N}_2 \mathrm{O}_5(g) is monitored as it decomposes, and the concentration of N2O5\mathrm{N}_2 \mathrm{O}_5 as a function of time is recorded. The results are shown in the table below.

Time (s) [N2O5]\mathrm{[N_2O_5]}
0 1.000
25.0 0.801
50.0 0.642
75.0 0.515

Calculate the average rate of the reaction between 50.050.0 and 75.075.0 seconds.

Solution

a A+b BcC+dDa \mathrm{~A}+b \mathrm{~B} \rightarrow c \mathrm{C}+d \mathrm{D}

the rate of reaction is defined as

 rate =1aΔ[A]Δt=1bΔ[B]Δt=+1cΔ[C]Δt=+1dΔ[D]Δt\color{cyan}\text { rate }=-\frac{1}{a} \frac{\Delta[\mathrm{A}]}{\Delta t}=-\frac{1}{b} \frac{\Delta[\mathrm{B}]}{\Delta t}=+\frac{1}{c} \frac{\Delta[\mathrm{C}]}{\Delta t}=+\frac{1}{d} \frac{\Delta[\mathrm{D}]}{\Delta t}

Notice that the rate of change in concentration of each species is divided by its coefficient from the balanced chemical equation ( aa, b,cb, c, or dd ). This ensures that the calculated reaction rate is the same no matter which reactant or product is monitored for changes in concentration. In this case, the monitored species was N2O5\mathrm{N}_2 \mathrm{O}_5. With that in mind, let's write the reaction rate in terms of the rate of change in concentration of N2O5\mathrm{N}_2 \mathrm{O}_5 :

 rate =12Δ[N2O5]Δt\text { rate }=-\frac{1}{2} \frac{\Delta\left[\mathrm{N}_2 \mathrm{O}_5\right]}{\Delta t}

Since the coefficient for N2O5\mathrm{N}_2 \mathrm{O}_5 in the balanced equation is 2 , we divided the rate of change in concentration of N2O5\mathrm{N}_2 \mathrm{O}_5 by 2 . Additionally, since N2O5\mathrm{N}_2 \mathrm{O}_5 is being consumed in the reaction, we included a negative sign in front of the expression.

Now, let's plug in the information from the table to calculate the average reaction rate between 50.050.0 and 75.075.0 seconds:

 rate =12(0.515M0.642M)(75.0 s50.0 s)=2.54×103M s1\begin{aligned} \text { rate } & =-\frac{1}{2} \frac{(0.515 M-0.642 M)}{(75.0 \mathrm{~s}-50.0 \mathrm{~s})} \\ & =2.54 \times 10^{-3} M \mathrm{~s}^{-1} \end{aligned}

So, the average rate of the reaction between 50.050.0 and 75.075.0 seconds is 2.54×103Ms1\bold{2.54 \times 10^{-3} \mathrm{M} \mathrm{s}^{-1}}.

]]>
Problem: 03-02-1

Question

2 N2O5(g)4NO2(g)+O2(g)2 \mathrm{~N}_2 \mathrm{O}_5(g) \rightarrow 4 \mathrm{NO}_2(g)+\mathrm{O}_2(g)

The decomposition of N2O5(g)\mathrm{N}_2 \mathrm{O}_5(g) is represented by the equation above. A sample of N2O5(g)\mathrm{N}_2 \mathrm{O}_5(g) is monitored as it decomposes, and the concentration of N2O5\mathrm{N}_2 \mathrm{O}_5 as a function of time is recorded. The results are shown in the table below.

Time (s) [N2O5]\mathrm{[N_2O_5]}
0 1.000
25.0 0.801
50.0 0.642
75.0 0.515

Calculate the average rate of the reaction between 50.050.0 and 75.075.0 seconds.

Solution

a A+b BcC+dDa \mathrm{~A}+b \mathrm{~B} \rightarrow c \mathrm{C}+d \mathrm{D}

the rate of reaction is defined as

 rate =1aΔ[A]Δt=1bΔ[B]Δt=+1cΔ[C]Δt=+1dΔ[D]Δt\color{cyan}\text { rate }=-\frac{1}{a} \frac{\Delta[\mathrm{A}]}{\Delta t}=-\frac{1}{b} \frac{\Delta[\mathrm{B}]}{\Delta t}=+\frac{1}{c} \frac{\Delta[\mathrm{C}]}{\Delta t}=+\frac{1}{d} \frac{\Delta[\mathrm{D}]}{\Delta t}

Notice that the rate of change in concentration of each species is divided by its coefficient from the balanced chemical equation ( aa, b,cb, c, or dd ). This ensures that the calculated reaction rate is the same no matter which reactant or product is monitored for changes in concentration. In this case, the monitored species was N2O5\mathrm{N}_2 \mathrm{O}_5. With that in mind, let's write the reaction rate in terms of the rate of change in concentration of N2O5\mathrm{N}_2 \mathrm{O}_5 :

 rate =12Δ[N2O5]Δt\text { rate }=-\frac{1}{2} \frac{\Delta\left[\mathrm{N}_2 \mathrm{O}_5\right]}{\Delta t}

Since the coefficient for N2O5\mathrm{N}_2 \mathrm{O}_5 in the balanced equation is 2 , we divided the rate of change in concentration of N2O5\mathrm{N}_2 \mathrm{O}_5 by 2 . Additionally, since N2O5\mathrm{N}_2 \mathrm{O}_5 is being consumed in the reaction, we included a negative sign in front of the expression.

Now, let's plug in the information from the table to calculate the average reaction rate between 50.050.0 and 75.075.0 seconds:

 rate =12(0.515M0.642M)(75.0 s50.0 s)=2.54×103M s1\begin{aligned} \text { rate } & =-\frac{1}{2} \frac{(0.515 M-0.642 M)}{(75.0 \mathrm{~s}-50.0 \mathrm{~s})} \\ & =2.54 \times 10^{-3} M \mathrm{~s}^{-1} \end{aligned}

So, the average rate of the reaction between 50.050.0 and 75.075.0 seconds is 2.54×103Ms1\bold{2.54 \times 10^{-3} \mathrm{M} \mathrm{s}^{-1}}.

]]>
<![CDATA[Problem: 03-02-2 ]]> https://note.toshiki.dev/academic/chemistry/problems/03-02-2 https://note.toshiki.dev/academic/chemistry/problems/03-02-2 Thu, 01 Jul 2021 00:00:00 GMT Problem: 03-02-2

Question

The rate law for a particular reaction is rate =k[XY]2=k[\mathrm{XY}]^2. In an experiment, the initial rate of the reaction is determined to be 0.16 mol/(Ls)0.16 \mathrm{~mol} /(\mathrm{L} \cdot \mathrm{s}) when the initial concentration of XY\mathrm{XY} is 0.40 mol/L0.40 \mathrm{~mol} / \mathrm{L}.

  • What is the value of the rate constant, kk, for the reaction?
    • 0.10 L/(mols)0.10 \mathrm{~L} /(\mathrm{mol} \cdot \mathrm{s})
    • 0.40 L/(mols)0.40 \mathrm{~L} /(\mathrm{mol} \cdot \mathrm{s})
    • 1.0 L/(mols)1.0 \mathrm{~L} /(\mathrm{mol} \cdot \mathrm{s})
    • 2.5 L/(mols)2.5 \mathrm{~L} /(\mathrm{mol} \cdot \mathrm{s})

Solution

lo tind the value of the rate constant for the reaction, let's first solve the rate law for kk :

k= rate [XY]2k=\frac{\text { rate }}{[\mathrm{XY}]^2}

Next, let's plug in the initial rate and concentration given in the text:

k=0.16 mol/(Ls)(0.40 mol/L)2=0.16 mol/(Ls)0.16 mol2/L2=1.0 L/(mols)\begin{aligned} k & =\frac{0.16 \mathrm{~mol} /(\mathrm{L} \cdot \mathrm{s})}{(0.40 \mathrm{~mol} / \mathrm{L})^2} \\ & =\frac{0.16 \mathrm{~mol} /(\mathrm{L} \cdot \mathrm{s})}{0.16 \mathrm{~mol}^2 / \mathrm{L}^2} \\ & =1.0 \mathrm{~L} /(\mathrm{mol} \cdot \mathrm{s}) \end{aligned}

So, the value of the rate constant for the reaction is 1.0 L/(mols)1.0 \mathrm{~L} /(\mathrm{mol} \cdot \mathrm{s})

]]>
Problem: 03-02-2

Question

The rate law for a particular reaction is rate =k[XY]2=k[\mathrm{XY}]^2. In an experiment, the initial rate of the reaction is determined to be 0.16 mol/(Ls)0.16 \mathrm{~mol} /(\mathrm{L} \cdot \mathrm{s}) when the initial concentration of XY\mathrm{XY} is 0.40 mol/L0.40 \mathrm{~mol} / \mathrm{L}.

  • What is the value of the rate constant, kk, for the reaction?
    • 0.10 L/(mols)0.10 \mathrm{~L} /(\mathrm{mol} \cdot \mathrm{s})
    • 0.40 L/(mols)0.40 \mathrm{~L} /(\mathrm{mol} \cdot \mathrm{s})
    • 1.0 L/(mols)1.0 \mathrm{~L} /(\mathrm{mol} \cdot \mathrm{s})
    • 2.5 L/(mols)2.5 \mathrm{~L} /(\mathrm{mol} \cdot \mathrm{s})

Solution

lo tind the value of the rate constant for the reaction, let's first solve the rate law for kk :

k= rate [XY]2k=\frac{\text { rate }}{[\mathrm{XY}]^2}

Next, let's plug in the initial rate and concentration given in the text:

k=0.16 mol/(Ls)(0.40 mol/L)2=0.16 mol/(Ls)0.16 mol2/L2=1.0 L/(mols)\begin{aligned} k & =\frac{0.16 \mathrm{~mol} /(\mathrm{L} \cdot \mathrm{s})}{(0.40 \mathrm{~mol} / \mathrm{L})^2} \\ & =\frac{0.16 \mathrm{~mol} /(\mathrm{L} \cdot \mathrm{s})}{0.16 \mathrm{~mol}^2 / \mathrm{L}^2} \\ & =1.0 \mathrm{~L} /(\mathrm{mol} \cdot \mathrm{s}) \end{aligned}

So, the value of the rate constant for the reaction is 1.0 L/(mols)1.0 \mathrm{~L} /(\mathrm{mol} \cdot \mathrm{s})

]]>
<![CDATA[Problem 03-02-3 ]]> https://note.toshiki.dev/academic/chemistry/problems/03-02-3 https://note.toshiki.dev/academic/chemistry/problems/03-02-3 Thu, 01 Jul 2021 00:00:00 GMT Problem 03-02-3

Question

2X(g)+2Y(g)Q(g)+2R(g)2 \mathrm{X}(g)+2 \mathrm{Y}(g) \rightarrow \mathrm{Q}(g)+2 \mathrm{R}(g)

The reaction represented above is found to be second order with respect to X\mathrm{X} and first order with respect to Y\mathrm{Y}.

What happens to the rate of the reaction when [X][\mathrm{X}] is halved and [Y][\mathrm{Y}] is doubled?

  • It increases by a factor of 4.
  • It decreases by a factor of 2.
  • It decreases by a factor of 4.
  • It does not change.

Solution

To solve this problem, let's first write out the rate law for the reaction. According to the text, the reaction is second order with respect to X\mathrm{X} and first order with respect to Y\mathrm{Y}, so the rate law is rate =k[X]2[Y]=k[\mathrm{X}]^2[\mathrm{Y}]

Now, let's think about how the rate changes when [X][\mathrm{X}] is halved and [Y][\mathrm{Y}] is doubled. Since [X][\mathrm{X}] is raised to the second power in the rate law, halving [X][\mathrm{X}] decreases the reaction rate by a factor of 4 . Similarly, since [Y][\mathrm{Y}] is raised to the first power, doubling [Y][\mathrm{Y}] increases the reaction rate by a factor of 2 . Combined, these changes result in the reaction rate decreasing by a factor of 2 overall. So, when [X][\mathrm{X}] is halved and [Y][\mathrm{Y}] is doubled, the rate of the reaction decreases by a factor of 2 .

]]>
Problem 03-02-3

Question

2X(g)+2Y(g)Q(g)+2R(g)2 \mathrm{X}(g)+2 \mathrm{Y}(g) \rightarrow \mathrm{Q}(g)+2 \mathrm{R}(g)

The reaction represented above is found to be second order with respect to X\mathrm{X} and first order with respect to Y\mathrm{Y}.

What happens to the rate of the reaction when [X][\mathrm{X}] is halved and [Y][\mathrm{Y}] is doubled?

  • It increases by a factor of 4.
  • It decreases by a factor of 2.
  • It decreases by a factor of 4.
  • It does not change.

Solution

To solve this problem, let's first write out the rate law for the reaction. According to the text, the reaction is second order with respect to X\mathrm{X} and first order with respect to Y\mathrm{Y}, so the rate law is rate =k[X]2[Y]=k[\mathrm{X}]^2[\mathrm{Y}]

Now, let's think about how the rate changes when [X][\mathrm{X}] is halved and [Y][\mathrm{Y}] is doubled. Since [X][\mathrm{X}] is raised to the second power in the rate law, halving [X][\mathrm{X}] decreases the reaction rate by a factor of 4 . Similarly, since [Y][\mathrm{Y}] is raised to the first power, doubling [Y][\mathrm{Y}] increases the reaction rate by a factor of 2 . Combined, these changes result in the reaction rate decreasing by a factor of 2 overall. So, when [X][\mathrm{X}] is halved and [Y][\mathrm{Y}] is doubled, the rate of the reaction decreases by a factor of 2 .

]]>
<![CDATA[CIS105: Computer Applications & Information Systems Lec. 1. ]]> https://note.toshiki.dev/academic/cis105/cis105-l1-lecture-note https://note.toshiki.dev/academic/cis105/cis105-l1-lecture-note Thu, 01 Jul 2021 00:00:00 GMT CIS105: Computer Applications & Information Systems Lec. 1.

Chapter 1: Everything Changes

1.1: The Historic Timelines

  • 1903: Wright bros, invented the airplane.

  • 1969: Armstrong walks on the moon.

  • 2004: SpaceX Falcon 9 lands upright.

  • 2015: Electreic plane crosses English Channel

  • 20xx: Google Live goes online.

  • Boeing 777, commercial airline airplanes normally cost approximately $200,000,000,000\$ 200,000,000,000 for a singular aircraft.

1.2: Analytical Engne

A mechanical computing device, was a special-purpose machine designed to tabulate logarithms and trigonometric functions by evaluating finite differences to create approximating polynomials.

1.3: Ada Lovelace

It tok the powerful insights of a mathematicial named Ada Lovelace to realize the true potentilal of the analytical engine. She was the first person to recognize that the machine could be used for more than pure calculations. She developed the first algorithm for the engine. It was the very first example of computer programming.

1.4: Information Technology is for People

  • Information technology (IT): the study, design, development, implementation, support, and management of computer-baed information systems, particularly software hardware.
    • People are the most important component in an information system because it is only a human who can conceive information from data. Computer system is only a machinery device and human is expected to operate towards aspects on how to perform, what to perform, what to outcome.
  • End-users (people) are what make computers start.
  • Attitude will be the defining factor in your success when it comes to computer competency.
  • Best practice: a management process, technique, or method that is most effective at arriving at desired outcome or better outcome than any other process, technique, or method.
    • The best and effective way of practice is through persistent and consistent training and reviewing.

1.5: Moore's Law

  • Gordon Moore: One of the founding fathers of the Intel.
  • Computer power doubles every eighteen months.
    • This essentially means that, if a business purchases a computer today, in eighteen months there will be a computer available that is twice as fast.
  • Being a Leader vs. Follower controversy

1.6: The Cuff Smartwatch?

US rapper/producer/entrepreneur Will.i.Am announced his foray into the world of wearable tech in 2014, proclaiming to have created a device so life-changing and futuristic it'd blow our archaic mind.

1.7: Types of Computer

  • Mainframe: Banks, Tech Companies
  • Midrange: Small to Mid-sized business, not as powerful.
  • Microcomputer: Laptops, Desktops, Tablet & Handled.

1.8: What is System Software?

  • System software vs. Operating system

  • System software vs. Application software

  • Operating system: Manages resources. Responsible for reading and writing data.

  • Graphical User Interface (GUI) & Command line interface.

    • The level of an operational system layers by interface visibility.

      • mermaid
        graph LR;
        a[GUI] --> b[Application software];
        b --> c[Operating system];
        c --> d[System software];
        d --> e[CLI]
        graph LR;
        a[GUI] --> b[Application software];
        b --> c[Operating system];
        c --> d[System software];
        d --> e[CLI]

1.9: Operating Systems/Platforms

  • A collection of computer programs that work together to manage hardware and software to ensure that they are working properly.
    • Memory allocation
    • Administer input and output of information
    • File management
  • Platform (OS): Microsoft Windows, macOS, iOS, Linux, UNIX.

2.0: Processes/Multitasking

  • Process: Any task a computer performs.
  • Multitasking: the execution of multiple processes over a certain period of time.

2.1: Memory/Disk management

  • Operating systems: Cache, random access memory (ram), registers, virtual memory.

  • Primary storage vs. Secondary Storage: RAM, hard drive, file allocation table (FAT).

    • The table of contents of a hard drive, or the file system directory structure of a system.
    • Primary storage is accessed randomly which indicating the storage is only temporary without preserved.

    • Secondary storage is the permanent storage on a specific device while user information is stored on the machine within the physical drive storage.

2.2: Business Computing Software

  • Software suite: Spreadsheets, word processors, database, and presentation software (aka application suite or productivity suite).

    • Sharing information between these applications is te mot important aspect of a software suite.
  • Hot keys/shortcuts: Ctrl+ C & Ctrl + V on Windows; Command+ C & Command + V on Windows.

  • Object linking and embedding (OLE) (Static)

    • In static linking, the system linker copies the dependencies into the final executable. At the time of linking an external library, the linker finds all dependencies that are defined in that library. And it replaces them with the corresponding functions from the library to resolve dependencies in our code. Afterward, the linker generates the final executable file that we can execute on the underlying machine.

      For example, let’s say our application calls the function print() from an external library named Library. The assembler generates the object file with all native symbols resolved to their memory addresses. The external reference print() cannot be resolved. The linker loads this library and finds the definition of print() in it. Then, it maps to print() to a memory location and thus resolves the dependency:

      Static Linking

      So, a statically linked file contains our program’s code as well as the code of all the libraries it invokes. Since we copy complete libraries, we need space on both the disk and in the main memory because the resulting file may be very large.

  • Object linking (Dynamic)

    • In dynamic linking, we copy the names of the external libraries into our final executable as unresolved symbols. We do the actual linking of these unresolved symbols only at runtime. How? When encountering an unresolved symbol, we query RAM for it. If the corresponding library isn’t loaded, the operating system loads it in the memory. So, the operating system performs dynamic linking for us by resolving each external symbol on the first muss. As a result, we load only a single copy of a library in memory and all processes use it.
]]>
CIS105: Computer Applications & Information Systems Lec. 1.

Chapter 1: Everything Changes

1.1: The Historic Timelines

  • 1903: Wright bros, invented the airplane.

  • 1969: Armstrong walks on the moon.

  • 2004: SpaceX Falcon 9 lands upright.

  • 2015: Electreic plane crosses English Channel

  • 20xx: Google Live goes online.

  • Boeing 777, commercial airline airplanes normally cost approximately $200,000,000,000\$ 200,000,000,000 for a singular aircraft.

1.2: Analytical Engne

A mechanical computing device, was a special-purpose machine designed to tabulate logarithms and trigonometric functions by evaluating finite differences to create approximating polynomials.

1.3: Ada Lovelace

It tok the powerful insights of a mathematicial named Ada Lovelace to realize the true potentilal of the analytical engine. She was the first person to recognize that the machine could be used for more than pure calculations. She developed the first algorithm for the engine. It was the very first example of computer programming.

1.4: Information Technology is for People

  • Information technology (IT): the study, design, development, implementation, support, and management of computer-baed information systems, particularly software hardware.
    • People are the most important component in an information system because it is only a human who can conceive information from data. Computer system is only a machinery device and human is expected to operate towards aspects on how to perform, what to perform, what to outcome.
  • End-users (people) are what make computers start.
  • Attitude will be the defining factor in your success when it comes to computer competency.
  • Best practice: a management process, technique, or method that is most effective at arriving at desired outcome or better outcome than any other process, technique, or method.
    • The best and effective way of practice is through persistent and consistent training and reviewing.

1.5: Moore's Law

  • Gordon Moore: One of the founding fathers of the Intel.
  • Computer power doubles every eighteen months.
    • This essentially means that, if a business purchases a computer today, in eighteen months there will be a computer available that is twice as fast.
  • Being a Leader vs. Follower controversy

1.6: The Cuff Smartwatch?

US rapper/producer/entrepreneur Will.i.Am announced his foray into the world of wearable tech in 2014, proclaiming to have created a device so life-changing and futuristic it'd blow our archaic mind.

1.7: Types of Computer

  • Mainframe: Banks, Tech Companies
  • Midrange: Small to Mid-sized business, not as powerful.
  • Microcomputer: Laptops, Desktops, Tablet & Handled.

1.8: What is System Software?

  • System software vs. Operating system

  • System software vs. Application software

  • Operating system: Manages resources. Responsible for reading and writing data.

  • Graphical User Interface (GUI) & Command line interface.

    • The level of an operational system layers by interface visibility.

      • mermaid
        graph LR;
        a[GUI] --> b[Application software];
        b --> c[Operating system];
        c --> d[System software];
        d --> e[CLI]
        graph LR;
        a[GUI] --> b[Application software];
        b --> c[Operating system];
        c --> d[System software];
        d --> e[CLI]

1.9: Operating Systems/Platforms

  • A collection of computer programs that work together to manage hardware and software to ensure that they are working properly.
    • Memory allocation
    • Administer input and output of information
    • File management
  • Platform (OS): Microsoft Windows, macOS, iOS, Linux, UNIX.

2.0: Processes/Multitasking

  • Process: Any task a computer performs.
  • Multitasking: the execution of multiple processes over a certain period of time.

2.1: Memory/Disk management

  • Operating systems: Cache, random access memory (ram), registers, virtual memory.

  • Primary storage vs. Secondary Storage: RAM, hard drive, file allocation table (FAT).

    • The table of contents of a hard drive, or the file system directory structure of a system.
    • Primary storage is accessed randomly which indicating the storage is only temporary without preserved.

    • Secondary storage is the permanent storage on a specific device while user information is stored on the machine within the physical drive storage.

2.2: Business Computing Software

  • Software suite: Spreadsheets, word processors, database, and presentation software (aka application suite or productivity suite).

    • Sharing information between these applications is te mot important aspect of a software suite.
  • Hot keys/shortcuts: Ctrl+ C & Ctrl + V on Windows; Command+ C & Command + V on Windows.

  • Object linking and embedding (OLE) (Static)

    • In static linking, the system linker copies the dependencies into the final executable. At the time of linking an external library, the linker finds all dependencies that are defined in that library. And it replaces them with the corresponding functions from the library to resolve dependencies in our code. Afterward, the linker generates the final executable file that we can execute on the underlying machine.

      For example, let’s say our application calls the function print() from an external library named Library. The assembler generates the object file with all native symbols resolved to their memory addresses. The external reference print() cannot be resolved. The linker loads this library and finds the definition of print() in it. Then, it maps to print() to a memory location and thus resolves the dependency:

      Static Linking

      So, a statically linked file contains our program’s code as well as the code of all the libraries it invokes. Since we copy complete libraries, we need space on both the disk and in the main memory because the resulting file may be very large.

  • Object linking (Dynamic)

    • In dynamic linking, we copy the names of the external libraries into our final executable as unresolved symbols. We do the actual linking of these unresolved symbols only at runtime. How? When encountering an unresolved symbol, we query RAM for it. If the corresponding library isn’t loaded, the operating system loads it in the memory. So, the operating system performs dynamic linking for us by resolving each external symbol on the first muss. As a result, we load only a single copy of a library in memory and all processes use it.
]]>
<![CDATA[CIS105: Computer Applications & Information Systems Lect. 10 ]]> https://note.toshiki.dev/academic/cis105/cis105-l10-lecture-note https://note.toshiki.dev/academic/cis105/cis105-l10-lecture-note Thu, 01 Jul 2021 00:00:00 GMT CIS105: Computer Applications & Information Systems Lect. 10

Chapter 10: Business Websites

10.1: Business Website Alternative

  • Web development platforms (WDP): Website creation programs that help non-web developers develop a website for a relatively low price.
    • Web.com, Wix.com, Squarespace.com
    • A great option for business owners
    • Search Engine Optimization

10.2: Early Website Technology

  • Who created Hypertext Markup Language (HTML)?
  • HTML is platform-neutral
  • What happens when you use the internet:
    • You don't visit websites, websites visit you
    • Copies of request kept in client's cache
mermaid
graph LR
A[You click on hyperlink] --> B[Web server ses HTTP to send copy of request to client]
graph LR
A[You click on hyperlink] --> B[Web server ses HTTP to send copy of request to client]

10.3: Hypertext Markup Language

  • The principal programming language for browsers
  • Elements: HTML represented in the form of tags that are enclosed by brackets: </>
  • <meta></meta>: Used to help search engines
    • Will include info like web page's author, descriptions, and keywords
    • Called meta keywords or meta-words.
  • Link element: <a href="www.youtube.com">Youtube</a>
  • Image element: <img src="meadow.gif" alt="meadow"></img>
  • JavaScript: A client-side programming language used to build websites
    • Requires a Java-enabled browser to work
    • Ex: Countdown timer

10.4: Websites Styles & Categories

  • Website categories: Personal, Commercial, Governmental, and intranet
    • Static Website (AKA Brochure websites): Content typically designed with HTML; never changes
    • Dynamic Websites: Generate web pages directly from the server depending on the context of the user
      • Ex: Social Media
      • Much more difficult to program, but are much easier to maintain

10.5: Types of Websites

  • Blog: An online diary, originally called a web-log
  • Content Website: typically dispense original content and often supported by advertising
  • Corporate Website: Distribute info about a business
  • Commerce Website (AKA E-Commerce site): to sell goods and services online
  • Search Engine Website: Offers general information and intended to be the entryway to other websites
  • Gaming Website: Typically, games unto themselves; require plug-ins like Adobe Flash, JavaScript, and ActiveX
  • News Websites: Specifically devoted to providing news and commentary
  • School Websites: Typically used by teachers, students, parents, and administrators.
  • Video-sharing websites: Allow users to upload videos for a wider audience
    • Utilizes Users Datagram Protocol (UDP)

10.6: Website Online Software

  • HTML is not a powerful programming language
  • Fat Client: Provides rich functionality on the client side; independent of a central server
    • Ex: Microsoft programs
    • Pros: More functionality, very powerful
    • Cons: Expensive. Requires additional software and set up, requires more processing power
  • Thin Client: A client that depends on a server for computing processing
    • Ex: Web browsers
    • Pros: Platform neutral, cheaper to maintain, better distribution of info
    • Cons: Not as powerful, less functionality, requires refreshing from the user

10.7: Online Advertising

  • Online Advertising: A form of sponsorship that uses the WWW for delivering business-marketing strategies
  • Examples:
    • Search Engine Results
    • Native Advertising
    • Social Network Advertising
    • Banner advertisement
  • Purchasing Online Advertising
    • Cost Per Click (CPC)
    • Cost Per Thousand Impressions (CPM)
    • Cost Per Action (CPA)
]]>
CIS105: Computer Applications & Information Systems Lect. 10

Chapter 10: Business Websites

10.1: Business Website Alternative

  • Web development platforms (WDP): Website creation programs that help non-web developers develop a website for a relatively low price.
    • Web.com, Wix.com, Squarespace.com
    • A great option for business owners
    • Search Engine Optimization

10.2: Early Website Technology

  • Who created Hypertext Markup Language (HTML)?
  • HTML is platform-neutral
  • What happens when you use the internet:
    • You don't visit websites, websites visit you
    • Copies of request kept in client's cache
mermaid
graph LR
A[You click on hyperlink] --> B[Web server ses HTTP to send copy of request to client]
graph LR
A[You click on hyperlink] --> B[Web server ses HTTP to send copy of request to client]

10.3: Hypertext Markup Language

  • The principal programming language for browsers
  • Elements: HTML represented in the form of tags that are enclosed by brackets: </>
  • <meta></meta>: Used to help search engines
    • Will include info like web page's author, descriptions, and keywords
    • Called meta keywords or meta-words.
  • Link element: <a href="www.youtube.com">Youtube</a>
  • Image element: <img src="meadow.gif" alt="meadow"></img>
  • JavaScript: A client-side programming language used to build websites
    • Requires a Java-enabled browser to work
    • Ex: Countdown timer

10.4: Websites Styles & Categories

  • Website categories: Personal, Commercial, Governmental, and intranet
    • Static Website (AKA Brochure websites): Content typically designed with HTML; never changes
    • Dynamic Websites: Generate web pages directly from the server depending on the context of the user
      • Ex: Social Media
      • Much more difficult to program, but are much easier to maintain

10.5: Types of Websites

  • Blog: An online diary, originally called a web-log
  • Content Website: typically dispense original content and often supported by advertising
  • Corporate Website: Distribute info about a business
  • Commerce Website (AKA E-Commerce site): to sell goods and services online
  • Search Engine Website: Offers general information and intended to be the entryway to other websites
  • Gaming Website: Typically, games unto themselves; require plug-ins like Adobe Flash, JavaScript, and ActiveX
  • News Websites: Specifically devoted to providing news and commentary
  • School Websites: Typically used by teachers, students, parents, and administrators.
  • Video-sharing websites: Allow users to upload videos for a wider audience
    • Utilizes Users Datagram Protocol (UDP)

10.6: Website Online Software

  • HTML is not a powerful programming language
  • Fat Client: Provides rich functionality on the client side; independent of a central server
    • Ex: Microsoft programs
    • Pros: More functionality, very powerful
    • Cons: Expensive. Requires additional software and set up, requires more processing power
  • Thin Client: A client that depends on a server for computing processing
    • Ex: Web browsers
    • Pros: Platform neutral, cheaper to maintain, better distribution of info
    • Cons: Not as powerful, less functionality, requires refreshing from the user

10.7: Online Advertising

  • Online Advertising: A form of sponsorship that uses the WWW for delivering business-marketing strategies
  • Examples:
    • Search Engine Results
    • Native Advertising
    • Social Network Advertising
    • Banner advertisement
  • Purchasing Online Advertising
    • Cost Per Click (CPC)
    • Cost Per Thousand Impressions (CPM)
    • Cost Per Action (CPA)
]]>
<![CDATA[CIS105: Computer Applications & Information Systems Lect. 11 ]]> https://note.toshiki.dev/academic/cis105/cis105-l11-lecture-note https://note.toshiki.dev/academic/cis105/cis105-l11-lecture-note Thu, 01 Jul 2021 00:00:00 GMT CIS105: Computer Applications & Information Systems Lect. 11

Chapter 11: Computer Security

Midterm reminder: March 28th - 29th

  • Exam Review after Chapter 11KC
  • 40 new questions, 10 KC questions
    • Same format as last time

11.1: System Security & Computer Privacy

  • An unsecured computer is extremely easy to breach by any seasoned hacker
  • Computer Security: Concerned with risk management, confidentiality, integrity, and the availability of the electronic info processed and stored within a computing system
  • Risk Management: Includes the recognition, consequences, and assessment of risk to a computer's assets, and developing strategies to manage and protect them

11.2: Business System Threats

  • Intranet: A businesses' private version of the internet
  • The key aspect of an intranet is privacy
  • Firewall: Hardware and software working together to ensure that only authorized personnel can access the business' intranet

11.3: Firewall

  • Without a firewall, an intranet is just another part of the internet
  • Proxy Server: A special security computer that allows communication to flow in and out of an intranet to check for external threats
  • Two standard security practices for firewalls:
    • Default-Deny
    • Default-Allow

11.4: Malware Threats

  • The term "virus" comes from biology
  • Malware Motivations:
    • Experimental Malware
    • Worms
    • Trojan Horses
    • Spyware/Keylogging
    • Adware
    • Spamming
    • Denial-of-Service Attach (DoS)
      • The deadliest
    • Reverse Phishing - "Spear Phishing"

11.5: Malware Solutions

  • Antivirus Software
    • Norton AntiVirus
    • McAfee's VirusScan
  • System patches
  • Data Backup
  • Employee training

11.6: Internet Fraud

  • Internet fraud: Any fraudulent activity in an online setting
  • Google AdSense, Google's advertising network; the middleman between the advertiser and the website owner
  • Click Fraud: a program that automatically clicks on Ads
  • Purchase Scam: scammer asks seller to pay for shipping via credit card, cancels credit card after order has shipped
  • Most uncomplicated type of internet fraud
  • Phishing: Uses social engineering techniques to gain private information

11.7: Computer Privacy

  • Privacy: The ability of an individual to keep their personal information out of public view
  • Anonymous: One's personal identity Is not be known
  • Tracking Cookie: A small text file that tracks your interaction on a website
  • History files: A list of stored or cached websites on a user's computer

50% of the time an unsecured computer can be hacked, and a password can be guessed

11.8: Identity Theft

  • Identity theft: A crime concerning the unlawful practice of assuming another individual's identity
  • Ways to acquire personal information:
    • Shoulder Surfing
    • Dumpster Diving
  • SCAM
    • Stingy
    • Check
    • Ask
    • Maintain
  • ASU's Recommended Password Manager: Stache
    • Bitwarden, 1Password, Dashlane, Keeper, KeePass
]]>
CIS105: Computer Applications & Information Systems Lect. 11

Chapter 11: Computer Security

Midterm reminder: March 28th - 29th

  • Exam Review after Chapter 11KC
  • 40 new questions, 10 KC questions
    • Same format as last time

11.1: System Security & Computer Privacy

  • An unsecured computer is extremely easy to breach by any seasoned hacker
  • Computer Security: Concerned with risk management, confidentiality, integrity, and the availability of the electronic info processed and stored within a computing system
  • Risk Management: Includes the recognition, consequences, and assessment of risk to a computer's assets, and developing strategies to manage and protect them

11.2: Business System Threats

  • Intranet: A businesses' private version of the internet
  • The key aspect of an intranet is privacy
  • Firewall: Hardware and software working together to ensure that only authorized personnel can access the business' intranet

11.3: Firewall

  • Without a firewall, an intranet is just another part of the internet
  • Proxy Server: A special security computer that allows communication to flow in and out of an intranet to check for external threats
  • Two standard security practices for firewalls:
    • Default-Deny
    • Default-Allow

11.4: Malware Threats

  • The term "virus" comes from biology
  • Malware Motivations:
    • Experimental Malware
    • Worms
    • Trojan Horses
    • Spyware/Keylogging
    • Adware
    • Spamming
    • Denial-of-Service Attach (DoS)
      • The deadliest
    • Reverse Phishing - "Spear Phishing"

11.5: Malware Solutions

  • Antivirus Software
    • Norton AntiVirus
    • McAfee's VirusScan
  • System patches
  • Data Backup
  • Employee training

11.6: Internet Fraud

  • Internet fraud: Any fraudulent activity in an online setting
  • Google AdSense, Google's advertising network; the middleman between the advertiser and the website owner
  • Click Fraud: a program that automatically clicks on Ads
  • Purchase Scam: scammer asks seller to pay for shipping via credit card, cancels credit card after order has shipped
  • Most uncomplicated type of internet fraud
  • Phishing: Uses social engineering techniques to gain private information

11.7: Computer Privacy

  • Privacy: The ability of an individual to keep their personal information out of public view
  • Anonymous: One's personal identity Is not be known
  • Tracking Cookie: A small text file that tracks your interaction on a website
  • History files: A list of stored or cached websites on a user's computer

50% of the time an unsecured computer can be hacked, and a password can be guessed

11.8: Identity Theft

  • Identity theft: A crime concerning the unlawful practice of assuming another individual's identity
  • Ways to acquire personal information:
    • Shoulder Surfing
    • Dumpster Diving
  • SCAM
    • Stingy
    • Check
    • Ask
    • Maintain
  • ASU's Recommended Password Manager: Stache
    • Bitwarden, 1Password, Dashlane, Keeper, KeePass
]]>
<![CDATA[CIS105: Computer Applications & Information Systems Lect. 12 ]]> https://note.toshiki.dev/academic/cis105/cis105-l12-lecture-note https://note.toshiki.dev/academic/cis105/cis105-l12-lecture-note Thu, 01 Jul 2021 00:00:00 GMT CIS105: Computer Applications & Information Systems Lect. 12

Chapter 12: Introduction to SQL

12.1: SQL Getting Started

  • Capture the data
    • Point of Sale, Scanning, etc
  • Get the data into a database
    • Import from other systems
    • Direct input from forms
  • Extract the data
    • SQL
  • Use the data
    • Analysis systems
    • Reporting systems
  • SQL: The language of relational databases
    • Structured query Language

If you plan to analyze data for a business, there is a good chance it's stored in a data warehouse, and you will need to learn how to retrieve it yourself.

12.2: SQL Statement

  • SELECT: What fields (column) you want
    • fieldname: If the name is used in only one table
  • FROM: What table or tables contain the fields
  • ORDER BY: Sorting
  • DISTINCT: Use after SELECT when you only want to show each vale of the selected field(s) once
  • LIMIT: Use when you want to limit the number of records produced
]]>
CIS105: Computer Applications & Information Systems Lect. 12

Chapter 12: Introduction to SQL

12.1: SQL Getting Started

  • Capture the data
    • Point of Sale, Scanning, etc
  • Get the data into a database
    • Import from other systems
    • Direct input from forms
  • Extract the data
    • SQL
  • Use the data
    • Analysis systems
    • Reporting systems
  • SQL: The language of relational databases
    • Structured query Language

If you plan to analyze data for a business, there is a good chance it's stored in a data warehouse, and you will need to learn how to retrieve it yourself.

12.2: SQL Statement

  • SELECT: What fields (column) you want
    • fieldname: If the name is used in only one table
  • FROM: What table or tables contain the fields
  • ORDER BY: Sorting
  • DISTINCT: Use after SELECT when you only want to show each vale of the selected field(s) once
  • LIMIT: Use when you want to limit the number of records produced
]]>
<![CDATA[CIS105: Computer Applications & Information Systems Lect. 13 ]]> https://note.toshiki.dev/academic/cis105/cis105-l13-lecture-note https://note.toshiki.dev/academic/cis105/cis105-l13-lecture-note Thu, 01 Jul 2021 00:00:00 GMT CIS105: Computer Applications & Information Systems Lect. 13

Chapter 13: Information Systems in Business

13.1: Business Functions

  • What is the definition of a business
    • Accounting
    • Human Resources
    • Marketing
    • Research and Development (R&D)
    • Production
    • Collaboration is key

13.2: The Accounting Department

  • "The mathematics of business"
  • Generally Accepted Accounting Principles (GAAP)
  • Sarbanes-Oxley Act of 2002 (SOX)

13.3: The Human Resources Department

  • Management of employees
  • What is the most important asset of any business?

13.4: The Marketing Department

  • Promotion of a business' products
  • The Four P's of Marketing - E. Jerome McCarthy
    • Products
    • Pricing
    • Promotion
    • Placement

13.5: The Research & Development Department

  • If a business isn't growing, it's dying
  • Creative and systematic approach
    • AKA Brainstorming
  • Is this idea feasible?

13.6: The Production Department

  • The makers of the business
  • Tangible vs. Intangible

13.7: Information System Collaboration

  • Electronic Computing Tols
    • Discussion Boards
    • Instant Messaging
    • Texting
  • Video Conferencing Software
    • Webinar
  • Project Management Software
    • Microsoft Project
    • Gantt Chart
    • System Development Life Cycle (SDLC)
    • Unified Modeling Language (UML)
  • Knowledge Management Systems
  • Online Application Software
]]>
CIS105: Computer Applications & Information Systems Lect. 13

Chapter 13: Information Systems in Business

13.1: Business Functions

  • What is the definition of a business
    • Accounting
    • Human Resources
    • Marketing
    • Research and Development (R&D)
    • Production
    • Collaboration is key

13.2: The Accounting Department

  • "The mathematics of business"
  • Generally Accepted Accounting Principles (GAAP)
  • Sarbanes-Oxley Act of 2002 (SOX)

13.3: The Human Resources Department

  • Management of employees
  • What is the most important asset of any business?

13.4: The Marketing Department

  • Promotion of a business' products
  • The Four P's of Marketing - E. Jerome McCarthy
    • Products
    • Pricing
    • Promotion
    • Placement

13.5: The Research & Development Department

  • If a business isn't growing, it's dying
  • Creative and systematic approach
    • AKA Brainstorming
  • Is this idea feasible?

13.6: The Production Department

  • The makers of the business
  • Tangible vs. Intangible

13.7: Information System Collaboration

  • Electronic Computing Tols
    • Discussion Boards
    • Instant Messaging
    • Texting
  • Video Conferencing Software
    • Webinar
  • Project Management Software
    • Microsoft Project
    • Gantt Chart
    • System Development Life Cycle (SDLC)
    • Unified Modeling Language (UML)
  • Knowledge Management Systems
  • Online Application Software
]]>
<![CDATA[CIS105: Computer Applications & Information Systems Lect. 14 ]]> https://note.toshiki.dev/academic/cis105/cis105-l14-lecture-note https://note.toshiki.dev/academic/cis105/cis105-l14-lecture-note Thu, 01 Jul 2021 00:00:00 GMT CIS105: Computer Applications & Information Systems Lect. 14

Chapter 14: More SQL Statement

14.1: Statement Review

  • SELECT: What fields (column) you want
    • fieldname: If the name is used in only one table
  • FROM: What table or tables contain the fields
  • ORDER BY: Sorting
  • DISTINCT: Use after SELECT when you only want to show each vale of the selected field(s) once
  • LIMIT: Use when you want to limit the number of records produced

14.2: New SQL Statements

  • WHERE: Applies conditions, filters

    • WHERE clause conditions follow a pattern: field + comparison operator + value

    • sql
      WHERE crime.iucr_no = 420
      WHERE crime.iucr_no = 420
  • Comparison Operators:

    • > : Returns all records larger than the specified value
    • >=: Returns all records that are at least as large as the specified value (including the value)
    • < : Returns all records smaller than the specified value
    • <=: Returns all records that are at least as small as the specified value (including the value)
    • = : Returns all records that are exactly equal to the specified value
    • <>: Returns all records that are not equal to the specified value
  • NULL: An empty value

  • NOT: Can be used to create a condition that reverses the logic of any condition

    • Similar logic to the NOT function in Excel
  • AND: Both conditions must be met for row to be included in query

  • OR: Used to combine criteria when we want our results to mach any criteria

  • BETWEEN: Shorthand way to include values in a range

  • IN: Shorthand way to include values in a range

  • LIKE: Use this statement when you aren't sure of the values in a record

  • %: any combination of characters

    • %Keyword: ends with keyword
    • %Keyword%: looks for %keyword% anywhere in the record
    • Keyword%: starts with keyword
  • - substitutes for any single character

    • 't_p' would return 'tip', 'tap', or 'top''; but not 'stop'

    • 'p_st" would return 'past"', but not 'paste'

    • 'h__s_n' would return 'hanson', 'hensen', or 'hansen'; but not 'harrison' (note that 'h%s_n' would return 'harrison')

14.3: Rules to Remember

  • To combine AND and OR statements, you must follow the order of operations (AND 1st, OR 2nd)
    • If OR must be first, use ()
  • All words must be in between ('_'), ("_")
    • If your value contains a quotation, use double quotation or a /
    • All #s is left as-is
]]>
CIS105: Computer Applications & Information Systems Lect. 14

Chapter 14: More SQL Statement

14.1: Statement Review

  • SELECT: What fields (column) you want
    • fieldname: If the name is used in only one table
  • FROM: What table or tables contain the fields
  • ORDER BY: Sorting
  • DISTINCT: Use after SELECT when you only want to show each vale of the selected field(s) once
  • LIMIT: Use when you want to limit the number of records produced

14.2: New SQL Statements

  • WHERE: Applies conditions, filters

    • WHERE clause conditions follow a pattern: field + comparison operator + value

    • sql
      WHERE crime.iucr_no = 420
      WHERE crime.iucr_no = 420
  • Comparison Operators:

    • > : Returns all records larger than the specified value
    • >=: Returns all records that are at least as large as the specified value (including the value)
    • < : Returns all records smaller than the specified value
    • <=: Returns all records that are at least as small as the specified value (including the value)
    • = : Returns all records that are exactly equal to the specified value
    • <>: Returns all records that are not equal to the specified value
  • NULL: An empty value

  • NOT: Can be used to create a condition that reverses the logic of any condition

    • Similar logic to the NOT function in Excel
  • AND: Both conditions must be met for row to be included in query

  • OR: Used to combine criteria when we want our results to mach any criteria

  • BETWEEN: Shorthand way to include values in a range

  • IN: Shorthand way to include values in a range

  • LIKE: Use this statement when you aren't sure of the values in a record

  • %: any combination of characters

    • %Keyword: ends with keyword
    • %Keyword%: looks for %keyword% anywhere in the record
    • Keyword%: starts with keyword
  • - substitutes for any single character

    • 't_p' would return 'tip', 'tap', or 'top''; but not 'stop'

    • 'p_st" would return 'past"', but not 'paste'

    • 'h__s_n' would return 'hanson', 'hensen', or 'hansen'; but not 'harrison' (note that 'h%s_n' would return 'harrison')

14.3: Rules to Remember

  • To combine AND and OR statements, you must follow the order of operations (AND 1st, OR 2nd)
    • If OR must be first, use ()
  • All words must be in between ('_'), ("_")
    • If your value contains a quotation, use double quotation or a /
    • All #s is left as-is
]]>
<![CDATA[CIS105: Computer Applications & Information Systems Lect. 15 ]]> https://note.toshiki.dev/academic/cis105/cis105-l15-lecture-note https://note.toshiki.dev/academic/cis105/cis105-l15-lecture-note Thu, 01 Jul 2021 00:00:00 GMT CIS105: Computer Applications & Information Systems Lect. 15

Chapter 15: Business System Reporting

Final months schedule

  • Today 4/9: Chapter 15/16
  • Thursday 4/11: Final SQL Assessment
  • Tuesday 4/16; Final Lecture and Final Exam Review
  • Thursday 4/18: MKT
  • 4/23 & 4/26: Zoom Office Hours
  • Final Exam: 4/25 - 4/26
  • Final day to complete all missing assignments: 4/28

15.1: Business System Reporting

  • Defined as informaitonal output from an information system to facilitate decision-making.
  • Report are periodic in nature
    • Daily, weekly, monthly, etc
    • Demand / Ad Hoc Reports
  • Strategic vs. Tactical decisions
  • Three main aspects of reporting:
    • Reporting summarization levels
    • Analysis and predictive reporting
    • Management Level Reporting
  • Reporting Summarization Levels: The level of detail or summarization in the report
  • Transaction Processing System (TPS)
    • Uses databases to store data
    • Groundwork for all other reports
    • Highest level of detail
  • Analysis and Predictive Reporting
    • Use TPS as a foundation
    • Trend reporting
    • Graphical repors
    • Budget, forecast, and variance reports
  • Management Level reporting
    • Top-level executive reporting
    • Management reporting
    • Supervisory reporting

]]>
CIS105: Computer Applications & Information Systems Lect. 15

Chapter 15: Business System Reporting

Final months schedule

  • Today 4/9: Chapter 15/16
  • Thursday 4/11: Final SQL Assessment
  • Tuesday 4/16; Final Lecture and Final Exam Review
  • Thursday 4/18: MKT
  • 4/23 & 4/26: Zoom Office Hours
  • Final Exam: 4/25 - 4/26
  • Final day to complete all missing assignments: 4/28

15.1: Business System Reporting

  • Defined as informaitonal output from an information system to facilitate decision-making.
  • Report are periodic in nature
    • Daily, weekly, monthly, etc
    • Demand / Ad Hoc Reports
  • Strategic vs. Tactical decisions
  • Three main aspects of reporting:
    • Reporting summarization levels
    • Analysis and predictive reporting
    • Management Level Reporting
  • Reporting Summarization Levels: The level of detail or summarization in the report
  • Transaction Processing System (TPS)
    • Uses databases to store data
    • Groundwork for all other reports
    • Highest level of detail
  • Analysis and Predictive Reporting
    • Use TPS as a foundation
    • Trend reporting
    • Graphical repors
    • Budget, forecast, and variance reports
  • Management Level reporting
    • Top-level executive reporting
    • Management reporting
    • Supervisory reporting

]]>
<![CDATA[CIS105: Computer Applications & Information Systems Lect. 16 ]]> https://note.toshiki.dev/academic/cis105/cis105-l16-lecture-note https://note.toshiki.dev/academic/cis105/cis105-l16-lecture-note Thu, 01 Jul 2021 00:00:00 GMT CIS105: Computer Applications & Information Systems Lect. 16

Chapter 16: Information Technology Careers

16.1: IT Careers Intro

  • Information Technology (IT) is everywhere
  • A common axiom for IT professionals is "know the business"
  • Value-Added: Refers to the added value of a product or service over the cost of products and services.

16.2: Business IT Perception

  • IT department are responsible for servicing and enhancing all computing, technical assets, and intellectual property of a business organization
    • Service IT
    • IT consulting
  • IT is the glue that holds organizations together

16.3: Information Technology Jobs

  • Chief Information Officer (CIO): Te board-level head of Information Technology departments
    • AKA Chief Technology Officer (CTO)
    • Replaced 'IT Director' title
    • Highest paid technology position
  • Head Application Developers In charge of software application development teams that develop, design, program and test software applications.
  • System Development Life Cycle (SDLC): A process for creating and altering computer applications through an approach that includes planning, system analysis, design, implementation, and system maintenance
  • Unified Modeling Language (UML): set of graphical notation techniques to create computer models and applications. It could be said that UML is a "blueprint" for developing applications
    • Application Architects: design different parts of applications
    • Middleware
    • Programming Infrastructure

16.4: Information Technology Jobs Contd.

  • Database Administrators (DBAs): the wizards of databases and data requirements
  • Network Administrators
  • Senior Web Developers
  • Business Intelligence Analyst
  • Information Technology Staff Consultants
  • IT Auditors

All IT jobs require experience, a degree, or both*

16.5: Enterprise Resource Planning Solution

  • Enterprise Resource Planning (ERP): an overall software solution that attempts to get departments on the same page, allowing them to share information and more easily collaborate with each other

    • Advantages

      • Increase production, collab, & efficiency

      • Revenue cycles and order tracking more easily available; enhances decision making

    • Disadvantages

      • Must re-engineer own processes to fit ERP solutions
      • Expensive
      • Must have process for tracking new entries to prevent inaccurate data from entering the database
      • Difficult to modify

16.6: Unified Modeling Language

  • Use case scenarios: "Who" can do "what"
  • Object-Oriented Analysis (OOA): Is focused on what a computer system does
  • Object Oriented Design (OOD): Focused on how a computer system what it does
  • Sequence Diagrams: Illustrations that sow how computer processes related and interact with each other and in what order.

16.7: System Development Methodologies

  • System Development Life Cycle
    • Initiation
    • Concept Development
    • Planing
    • Requirements
    • Design
    • Development
    • Testing
    • Implementation
  • Rapid Application Development (RAD)
    • Develope as you go
  • Software Prototyping
    • Prototypes AKA vaporware
]]>
CIS105: Computer Applications & Information Systems Lect. 16

Chapter 16: Information Technology Careers

16.1: IT Careers Intro

  • Information Technology (IT) is everywhere
  • A common axiom for IT professionals is "know the business"
  • Value-Added: Refers to the added value of a product or service over the cost of products and services.

16.2: Business IT Perception

  • IT department are responsible for servicing and enhancing all computing, technical assets, and intellectual property of a business organization
    • Service IT
    • IT consulting
  • IT is the glue that holds organizations together

16.3: Information Technology Jobs

  • Chief Information Officer (CIO): Te board-level head of Information Technology departments
    • AKA Chief Technology Officer (CTO)
    • Replaced 'IT Director' title
    • Highest paid technology position
  • Head Application Developers In charge of software application development teams that develop, design, program and test software applications.
  • System Development Life Cycle (SDLC): A process for creating and altering computer applications through an approach that includes planning, system analysis, design, implementation, and system maintenance
  • Unified Modeling Language (UML): set of graphical notation techniques to create computer models and applications. It could be said that UML is a "blueprint" for developing applications
    • Application Architects: design different parts of applications
    • Middleware
    • Programming Infrastructure

16.4: Information Technology Jobs Contd.

  • Database Administrators (DBAs): the wizards of databases and data requirements
  • Network Administrators
  • Senior Web Developers
  • Business Intelligence Analyst
  • Information Technology Staff Consultants
  • IT Auditors

All IT jobs require experience, a degree, or both*

16.5: Enterprise Resource Planning Solution

  • Enterprise Resource Planning (ERP): an overall software solution that attempts to get departments on the same page, allowing them to share information and more easily collaborate with each other

    • Advantages

      • Increase production, collab, & efficiency

      • Revenue cycles and order tracking more easily available; enhances decision making

    • Disadvantages

      • Must re-engineer own processes to fit ERP solutions
      • Expensive
      • Must have process for tracking new entries to prevent inaccurate data from entering the database
      • Difficult to modify

16.6: Unified Modeling Language

  • Use case scenarios: "Who" can do "what"
  • Object-Oriented Analysis (OOA): Is focused on what a computer system does
  • Object Oriented Design (OOD): Focused on how a computer system what it does
  • Sequence Diagrams: Illustrations that sow how computer processes related and interact with each other and in what order.

16.7: System Development Methodologies

  • System Development Life Cycle
    • Initiation
    • Concept Development
    • Planing
    • Requirements
    • Design
    • Development
    • Testing
    • Implementation
  • Rapid Application Development (RAD)
    • Develope as you go
  • Software Prototyping
    • Prototypes AKA vaporware
]]>
<![CDATA[CIS105: Computer Applications & Information Systems Lect. 17 ]]> https://note.toshiki.dev/academic/cis105/cis105-l17-lecture-note https://note.toshiki.dev/academic/cis105/cis105-l17-lecture-note Thu, 01 Jul 2021 00:00:00 GMT CIS105: Computer Applications & Information Systems Lect. 17

Chapter 17: SQL Clauses: JOIN Query

17.1: JOIN & ON Clauses

  • JOIN: Join tables together to connect multiple fields into 1 query.
  • ON: Linking the primary and foreign key
  • Linking formula: FROM table1 + JOIN table2 ON table1.primarykey = table2.foreignkey
sql
SELECT first_name, last_name, link_to_major, major_id, major_name
	FROM member
	JOIN major
		ON member. link_to_major = major.major_id
SELECT first_name, last_name, link_to_major, major_id, major_name
	FROM member
	JOIN major
		ON member. link_to_major = major.major_id

17.2: SQL Statements: Primary vs. Foreign Keys

  • Primary key: A field on a database table that uniquely identifies each row of the table.
  • Foreign key: is used to combine the rows from one table wit the rows of another table.

17.3: SQL Statement: Date & Time Formatting

  • The common conventional format of SQL date & time searching is as followed, in form of YEAR-MONTH-DATT12:00:00

    • sql
      '2022-04-17T12:00:00'
      '2022-04-17T12:00:00'
]]>
CIS105: Computer Applications & Information Systems Lect. 17

Chapter 17: SQL Clauses: JOIN Query

17.1: JOIN & ON Clauses

  • JOIN: Join tables together to connect multiple fields into 1 query.
  • ON: Linking the primary and foreign key
  • Linking formula: FROM table1 + JOIN table2 ON table1.primarykey = table2.foreignkey
sql
SELECT first_name, last_name, link_to_major, major_id, major_name
	FROM member
	JOIN major
		ON member. link_to_major = major.major_id
SELECT first_name, last_name, link_to_major, major_id, major_name
	FROM member
	JOIN major
		ON member. link_to_major = major.major_id

17.2: SQL Statements: Primary vs. Foreign Keys

  • Primary key: A field on a database table that uniquely identifies each row of the table.
  • Foreign key: is used to combine the rows from one table wit the rows of another table.

17.3: SQL Statement: Date & Time Formatting

  • The common conventional format of SQL date & time searching is as followed, in form of YEAR-MONTH-DATT12:00:00

    • sql
      '2022-04-17T12:00:00'
      '2022-04-17T12:00:00'
]]>
<![CDATA[CIS105: Computer Applications & Information Systems Lect. 18 ]]> https://note.toshiki.dev/academic/cis105/cis105-l18-lecture-note https://note.toshiki.dev/academic/cis105/cis105-l18-lecture-note Thu, 01 Jul 2021 00:00:00 GMT CIS105: Computer Applications & Information Systems Lect. 18

Chapter 18: Databases

Housekeeping:

  • Zoom Office Hours: Tuesday April 23rd and 25th, no class starting today.

18.1: Datase Overview

  • Column = Field
    • AKA attributes
  • Tables hold database data
  • DBMS
  • Oracle

18.2: Database Structure

  • Entity Relationship Modeling (ERM): a database-modeling method used to construct a theoretical and conceptual representation of data to produce a schema.
    • Tables
    • Reports
    • Queries
    • Forms
  • DBAs still need to know the business.

18.3: Business Database Advantages

  • Data Validation
  • No Errors + No Repeats = Data Integrity
  • GIGO: Garbage-in-Garbage-Out

18.4: Structured Query language

  • Most widely used query language
  • SQL Clauses for updating fields:
    • APPEND
    • DELETE
    • UPDTE
]]>
CIS105: Computer Applications & Information Systems Lect. 18

Chapter 18: Databases

Housekeeping:

  • Zoom Office Hours: Tuesday April 23rd and 25th, no class starting today.

18.1: Datase Overview

  • Column = Field
    • AKA attributes
  • Tables hold database data
  • DBMS
  • Oracle

18.2: Database Structure

  • Entity Relationship Modeling (ERM): a database-modeling method used to construct a theoretical and conceptual representation of data to produce a schema.
    • Tables
    • Reports
    • Queries
    • Forms
  • DBAs still need to know the business.

18.3: Business Database Advantages

  • Data Validation
  • No Errors + No Repeats = Data Integrity
  • GIGO: Garbage-in-Garbage-Out

18.4: Structured Query language

  • Most widely used query language
  • SQL Clauses for updating fields:
    • APPEND
    • DELETE
    • UPDTE
]]>
<![CDATA[CIS105: Computer Applications & Information Systems Lect. 2 ]]> https://note.toshiki.dev/academic/cis105/cis105-l2-lecture-note https://note.toshiki.dev/academic/cis105/cis105-l2-lecture-note Thu, 01 Jul 2021 00:00:00 GMT CIS105: Computer Applications & Information Systems Lect. 2

Chapter 2: Application Software

  • An application program is a computer program designed to carry out a specific task other than one relating to the operation of the computer itself.

2.1: Word Processing Software

  • For creating, updating and editing documents
  • Can create a Table of Contents
  • Saved to secondary memory
  • Often underestimated
  • Microsoft Word: Most popular word processor in the world
  • Adobe Acrobat: Most portable document format (pdf)
    • Platform Neutral
  • Corel WordPerfect: most dominant in early 80s (still used in some industries like law)
    • Created and Brigham Young university

2.2: Spreadsheets

Microsoft Excel: Most popular spreadsheet application (provides "what-if" analysis)

  • Interface of information in a grid form
  • Separated by columns and rows
    • Intersection of both called a cell
  • Often for financial calculations
  • Supports graphing
  • Replaced Lotus 1-2-3 as industry standard in 1993

2.3: Database Software

Database: The heavy-lifting application

  • Well thought out collection of files
  • Consists of records (rows)
  • Separated by fields (columns)
  • Can be queried
  • Often called a Database Management System or simply referred as DBMS
  • One-to-many relationship

2.4: Presentation Software

  • Displays information
  • Often a slide show and on-screen
  • Easy to build
  • Popularized by Business Intelligence
  • Allows users to:
    • Edit, update, insert, and delete text
    • Include graphics, video, and hypertext

2.5: Browser Software

  • User interface software that allows the user to display web pages found on the World Wide Web
  • Browsers display hyperlinks that are clickable navigation elements
  • Microsoft Edge, Google Chroe, Mozilla Firefox, and Apple's Safari
  • The first browser was called WorldWideWeb (no spaces)
  • Sir Tim Berners-Lee was the inventor of the first web browser

2.6: Networks

  • A computer network is two or more computers connected together for resource sharing and communication.
  • Resources: Computer files, folder, software
  • Peripheral hardware: Printers, scanners, webcam, etc.

The advantages of a computer network over a stand-alone computer are so significant that business cannot compete effectively in the marketplace without a network of some kind, even if the business is a sole proprietorship.

]]>
CIS105: Computer Applications & Information Systems Lect. 2

Chapter 2: Application Software

  • An application program is a computer program designed to carry out a specific task other than one relating to the operation of the computer itself.

2.1: Word Processing Software

  • For creating, updating and editing documents
  • Can create a Table of Contents
  • Saved to secondary memory
  • Often underestimated
  • Microsoft Word: Most popular word processor in the world
  • Adobe Acrobat: Most portable document format (pdf)
    • Platform Neutral
  • Corel WordPerfect: most dominant in early 80s (still used in some industries like law)
    • Created and Brigham Young university

2.2: Spreadsheets

Microsoft Excel: Most popular spreadsheet application (provides "what-if" analysis)

  • Interface of information in a grid form
  • Separated by columns and rows
    • Intersection of both called a cell
  • Often for financial calculations
  • Supports graphing
  • Replaced Lotus 1-2-3 as industry standard in 1993

2.3: Database Software

Database: The heavy-lifting application

  • Well thought out collection of files
  • Consists of records (rows)
  • Separated by fields (columns)
  • Can be queried
  • Often called a Database Management System or simply referred as DBMS
  • One-to-many relationship

2.4: Presentation Software

  • Displays information
  • Often a slide show and on-screen
  • Easy to build
  • Popularized by Business Intelligence
  • Allows users to:
    • Edit, update, insert, and delete text
    • Include graphics, video, and hypertext

2.5: Browser Software

  • User interface software that allows the user to display web pages found on the World Wide Web
  • Browsers display hyperlinks that are clickable navigation elements
  • Microsoft Edge, Google Chroe, Mozilla Firefox, and Apple's Safari
  • The first browser was called WorldWideWeb (no spaces)
  • Sir Tim Berners-Lee was the inventor of the first web browser

2.6: Networks

  • A computer network is two or more computers connected together for resource sharing and communication.
  • Resources: Computer files, folder, software
  • Peripheral hardware: Printers, scanners, webcam, etc.

The advantages of a computer network over a stand-alone computer are so significant that business cannot compete effectively in the marketplace without a network of some kind, even if the business is a sole proprietorship.

]]>
<![CDATA[CIS105: Computer Applications & Information Systems Lect. 3 ]]> https://note.toshiki.dev/academic/cis105/cis105-l3-lecture-note https://note.toshiki.dev/academic/cis105/cis105-l3-lecture-note Thu, 01 Jul 2021 00:00:00 GMT CIS105: Computer Applications & Information Systems Lect. 3

Chapter 3: Computer Hardware

3.1: Technical Terminologies

  • System Unit: Main body of the computer that contains a motherboard.
  • Motherboard (AKA Circuit Board): Main component of a system unit; a compleex array of electronics that connect and help different components of the computer communicate with each other.
    • PC: Motherboards, Mac; Logic Boards
  • Chassis (AKA Case or Box): Case to enclose the main components of a computer
  • Microprocessor: The brains of the computer
    • Central processing unit (CPU): Interprets program instructions and processes data by performing arithmetic and logical operations.

3.2: Central Processing Unit (CPU)

  • Speed is directly, but not solely, related to the CPU
  • Measured in Clock Rate
    • The number of cycles per second, that a computer can perform its most basic task
  • RSIC (Reduced Instruction Set Computer): Many chips encased into one chip
  • Bus Lines; Pathways that transfer data and power between components inside of a computer.
Architecture Diagram of CPU Actual CPU Image
Architecture of the central processing unit (CPU) - Computer ... What Is a CPU? a Guide to Your Computer's 'Brain'

3.3 Power Supply Unit (PSU)

  • Supplies electricity
  • Converts 100-120 volts or 220-240 volts of alternating current (AC) to a lower voltage direct current (DC) that can be used by the internal components of the system unit
  • Different currents used in different parts of the world.

3.4: Primary and Secondary Storage

  • Primary: The workbench
    • Random Access Memory (RAM): Primary storage
  • Secondary: The storage for all your tools and supplies
    • Hard Drive: Secondary storage
  • ROM Chips (Read-Only Memory): Preprogrammed chips that serve specialized internal tasks. No human intervention
    • AKA Firmware

3.4.1: Secondary Storage Contd.

  • Internal vs. External Storage
  • Hard Drivers vs. Solid State Drivers (SSDs)
  • Impractical for a computer to be stand-alone
  • Important to consider business needs
    • Bad IT can make or break a business

3.5: Binary Number System

  • Computer only understands one language: Machine code or machine language

  • 1 or 0 (on or off)

  • 1s or 0s are referred to as bits (short for binary digits)

  • 8 bits become a byte

    • Byte 8 bits
    • Kilob
  • American Standard Code for Information Interchange (ASCII): The coding scheme that most microcomputer use to represent bytes.

    • Name Equal To Size (In Bytes)
      Bit 1 Bit 1/8
      Nibble 4 Bits 1/2 (rare)
      Byte 8 Bits 1
      Kilobyte 1024 Bytes 1024
      Megabyte 1, 024 Kilobytes 1, 048, 576
      Gigabyte 1, 024 Megabytes 1, 073, 741, 824
      Terrabyte 1, 024 Gigabytes 1, 099, 511, 627, 776
      Petabyte 1, 024 Terabytes 1, 125, 899, 906, 842, 624
      Exabyte 1, 024 Petabytes 1, 152, 921, 504, 606, 846, 976
      Zettabyte 1, 024 Exabytes 1, 180, 591, 620, 717, 411, 303, 424
      Yottabyte 1, 024 Zettabytes 1, 208, 925, 819, 614, 629, 174, 706, 176

3.6: Peripheral Devices

  • Input v. Output
  • Input device: keywords, mice, touchpad, stylus, speakers, microphone, digital camera, etc/
  • Optical Character Recognition (OCR): Converting printed text to digital text
  • Radio Frequency Identification (RFID): An input mechanism that can be used to label a product for identification and have the product's information transmitted through radio waves.

3.7: Output Devices Contd.

  • Monitor: A series of transistors that translate machine code into text and images./
  • Pixels: A single dot on a graphic or text image
  • Resolution: The number of pixels inside a defined dimension on a monitor, commonly referred to as dots per inch (dpi).
    • Resolution is the most important feature of a monitor.
]]>
CIS105: Computer Applications & Information Systems Lect. 3

Chapter 3: Computer Hardware

3.1: Technical Terminologies

  • System Unit: Main body of the computer that contains a motherboard.
  • Motherboard (AKA Circuit Board): Main component of a system unit; a compleex array of electronics that connect and help different components of the computer communicate with each other.
    • PC: Motherboards, Mac; Logic Boards
  • Chassis (AKA Case or Box): Case to enclose the main components of a computer
  • Microprocessor: The brains of the computer
    • Central processing unit (CPU): Interprets program instructions and processes data by performing arithmetic and logical operations.

3.2: Central Processing Unit (CPU)

  • Speed is directly, but not solely, related to the CPU
  • Measured in Clock Rate
    • The number of cycles per second, that a computer can perform its most basic task
  • RSIC (Reduced Instruction Set Computer): Many chips encased into one chip
  • Bus Lines; Pathways that transfer data and power between components inside of a computer.
Architecture Diagram of CPU Actual CPU Image
Architecture of the central processing unit (CPU) - Computer ... What Is a CPU? a Guide to Your Computer's 'Brain'

3.3 Power Supply Unit (PSU)

  • Supplies electricity
  • Converts 100-120 volts or 220-240 volts of alternating current (AC) to a lower voltage direct current (DC) that can be used by the internal components of the system unit
  • Different currents used in different parts of the world.

3.4: Primary and Secondary Storage

  • Primary: The workbench
    • Random Access Memory (RAM): Primary storage
  • Secondary: The storage for all your tools and supplies
    • Hard Drive: Secondary storage
  • ROM Chips (Read-Only Memory): Preprogrammed chips that serve specialized internal tasks. No human intervention
    • AKA Firmware

3.4.1: Secondary Storage Contd.

  • Internal vs. External Storage
  • Hard Drivers vs. Solid State Drivers (SSDs)
  • Impractical for a computer to be stand-alone
  • Important to consider business needs
    • Bad IT can make or break a business

3.5: Binary Number System

  • Computer only understands one language: Machine code or machine language

  • 1 or 0 (on or off)

  • 1s or 0s are referred to as bits (short for binary digits)

  • 8 bits become a byte

    • Byte 8 bits
    • Kilob
  • American Standard Code for Information Interchange (ASCII): The coding scheme that most microcomputer use to represent bytes.

    • Name Equal To Size (In Bytes)
      Bit 1 Bit 1/8
      Nibble 4 Bits 1/2 (rare)
      Byte 8 Bits 1
      Kilobyte 1024 Bytes 1024
      Megabyte 1, 024 Kilobytes 1, 048, 576
      Gigabyte 1, 024 Megabytes 1, 073, 741, 824
      Terrabyte 1, 024 Gigabytes 1, 099, 511, 627, 776
      Petabyte 1, 024 Terabytes 1, 125, 899, 906, 842, 624
      Exabyte 1, 024 Petabytes 1, 152, 921, 504, 606, 846, 976
      Zettabyte 1, 024 Exabytes 1, 180, 591, 620, 717, 411, 303, 424
      Yottabyte 1, 024 Zettabytes 1, 208, 925, 819, 614, 629, 174, 706, 176

3.6: Peripheral Devices

  • Input v. Output
  • Input device: keywords, mice, touchpad, stylus, speakers, microphone, digital camera, etc/
  • Optical Character Recognition (OCR): Converting printed text to digital text
  • Radio Frequency Identification (RFID): An input mechanism that can be used to label a product for identification and have the product's information transmitted through radio waves.

3.7: Output Devices Contd.

  • Monitor: A series of transistors that translate machine code into text and images./
  • Pixels: A single dot on a graphic or text image
  • Resolution: The number of pixels inside a defined dimension on a monitor, commonly referred to as dots per inch (dpi).
    • Resolution is the most important feature of a monitor.
]]>
<![CDATA[CIS105: Computer Applications & Information Systems Lect. 4 ]]> https://note.toshiki.dev/academic/cis105/cis105-l4-lecture-note https://note.toshiki.dev/academic/cis105/cis105-l4-lecture-note Thu, 01 Jul 2021 00:00:00 GMT CIS105: Computer Applications & Information Systems Lect. 4

Chapter 4: Formulas and Functions

4.1: References and Calculations

  • Calculations
    • Add (+), Subtract (-), Multiply (*), Divide (/)
    • Add: A1+A2
    • Subtract: A1-A2
    • Multiply: A1*A2
    • Divide: A1/A2
  • Always end typing by pressing Enter
  • Al formulas start with an equals (=) sign

4.2: References and Calculations

  • References: When we perform calculations in Excel, we often reference the value stored in other cells in our worksheet

  • Three ays to reference a cell:

    • Relative reference - A1
    • Mixed reference - $A1 or A$1
    • Absolute reference - $A$1
  • Relative Reference: An address or pointer that changes when the target item is moved or the relationship to it has changed.

    • RELATIVE REFERENCE IS THE DEFALT REFERENCE IN EXCEL.
    • The reference changes when the formula is copied elsewhere.
    • Excel sees the location of the cells relative to the location of the formula.
    • Click Fn + F4 as hotkeys to construct value as relative value
  • Absolute Reference: Will make either the row or column "constant" in other words, the ABSOLUTE cell location is LOCKED

    • To create an absolute cell reference, put a dollar sign ``$` symbol in front of the part of the reference that you want to remain constant.
  • Reference Comments
    A1 Both the column and row references are "relative" and will change when the reference is copied and pasted to other cell.
    $A1 The column reference is "absolute" and will remain constant when copied and pasted to other cells. The row reference is "relative" and will change when copied and pasted to cells in other rows of the worksheet
    A$1 The column reference is "relative" and will change when copied and pasted to cells in other columns in the worksheet. The row reference is "absolute" and will remain constant when copied and pasted to other cells.
    $A$1 Both the column and row references are "absolute" and will remain constant when the reference is copied and pated to other cells.

4.3: Summary Statistics Functions

  • Formula vs. Function
    • Formula: Any calculation in excel
    • Function: A pre-defined calculation
  • To perform calculations in Excel, we often reference the values stored in other cells in our worksheets. We reference the cell location, not the value in the cell.
  • COUNT(value1, [value2]), ...): Counts the number of cells in that contain numbers.
  • COUNTA(value1, [value2], ...): Counts the number of cells in a range of cells that are not blank.
  • AVERAGE(number1, [number2], ...): Calculates the simple average of a set of numbers.
  • MAX(number1, [number2], ...): Returns the largest value in a set of numbers.
  • MIN(number1, [number2], ...): Returns the smallest value in a set of numbers.

4.4: Financial Function

  • RATE(nper, pmt, pv, [fv], [type], [guess]) : calculates the interest rate earned for an investment given the number of payments made as part of the investment, the payment amount, and the current value of the investment.
  • EFFECT(nominal _rate, pery): calculates the annual percentage rate for an interest rate given the number of times per year that interest is charged.
  • NPER(rate, pmt, pv, [fv], [type]): calculates the number of payments that will be made to pay off a loan given the interest rate, payment amount, and original loan amount.
  • PMT(rate, per, pv, [fv], [type]): calculates the payment amount for a loan given the interest rate, number of payments to be made to pay off the loan, and the original loan amount.
  • PV(rate, per, pmt, [fv], (type)): calculates the current value (accounting for compounding interest) of an investment given the interest rate, number of payments to be made, and the amount of the payment.
  • FV(rate, per, pmt, [pv], [type]): calculates the future value of an investment given the interest rate, number of payments to be made, and the amount of the payment.
]]>
CIS105: Computer Applications & Information Systems Lect. 4

Chapter 4: Formulas and Functions

4.1: References and Calculations

  • Calculations
    • Add (+), Subtract (-), Multiply (*), Divide (/)
    • Add: A1+A2
    • Subtract: A1-A2
    • Multiply: A1*A2
    • Divide: A1/A2
  • Always end typing by pressing Enter
  • Al formulas start with an equals (=) sign

4.2: References and Calculations

  • References: When we perform calculations in Excel, we often reference the value stored in other cells in our worksheet

  • Three ays to reference a cell:

    • Relative reference - A1
    • Mixed reference - $A1 or A$1
    • Absolute reference - $A$1
  • Relative Reference: An address or pointer that changes when the target item is moved or the relationship to it has changed.

    • RELATIVE REFERENCE IS THE DEFALT REFERENCE IN EXCEL.
    • The reference changes when the formula is copied elsewhere.
    • Excel sees the location of the cells relative to the location of the formula.
    • Click Fn + F4 as hotkeys to construct value as relative value
  • Absolute Reference: Will make either the row or column "constant" in other words, the ABSOLUTE cell location is LOCKED

    • To create an absolute cell reference, put a dollar sign ``$` symbol in front of the part of the reference that you want to remain constant.
  • Reference Comments
    A1 Both the column and row references are "relative" and will change when the reference is copied and pasted to other cell.
    $A1 The column reference is "absolute" and will remain constant when copied and pasted to other cells. The row reference is "relative" and will change when copied and pasted to cells in other rows of the worksheet
    A$1 The column reference is "relative" and will change when copied and pasted to cells in other columns in the worksheet. The row reference is "absolute" and will remain constant when copied and pasted to other cells.
    $A$1 Both the column and row references are "absolute" and will remain constant when the reference is copied and pated to other cells.

4.3: Summary Statistics Functions

  • Formula vs. Function
    • Formula: Any calculation in excel
    • Function: A pre-defined calculation
  • To perform calculations in Excel, we often reference the values stored in other cells in our worksheets. We reference the cell location, not the value in the cell.
  • COUNT(value1, [value2]), ...): Counts the number of cells in that contain numbers.
  • COUNTA(value1, [value2], ...): Counts the number of cells in a range of cells that are not blank.
  • AVERAGE(number1, [number2], ...): Calculates the simple average of a set of numbers.
  • MAX(number1, [number2], ...): Returns the largest value in a set of numbers.
  • MIN(number1, [number2], ...): Returns the smallest value in a set of numbers.

4.4: Financial Function

  • RATE(nper, pmt, pv, [fv], [type], [guess]) : calculates the interest rate earned for an investment given the number of payments made as part of the investment, the payment amount, and the current value of the investment.
  • EFFECT(nominal _rate, pery): calculates the annual percentage rate for an interest rate given the number of times per year that interest is charged.
  • NPER(rate, pmt, pv, [fv], [type]): calculates the number of payments that will be made to pay off a loan given the interest rate, payment amount, and original loan amount.
  • PMT(rate, per, pv, [fv], [type]): calculates the payment amount for a loan given the interest rate, number of payments to be made to pay off the loan, and the original loan amount.
  • PV(rate, per, pmt, [fv], (type)): calculates the current value (accounting for compounding interest) of an investment given the interest rate, number of payments to be made, and the amount of the payment.
  • FV(rate, per, pmt, [pv], [type]): calculates the future value of an investment given the interest rate, number of payments to be made, and the amount of the payment.
]]>
<![CDATA[CIS105: Computer Applications & Information Systems Lect. 5 ]]> https://note.toshiki.dev/academic/cis105/cis105-l5-lecture-note https://note.toshiki.dev/academic/cis105/cis105-l5-lecture-note Thu, 01 Jul 2021 00:00:00 GMT CIS105: Computer Applications & Information Systems Lect. 5

Chapter 5: Operating System

5.1: Operating System Fundamentals

  • 1980: Bill Gates and Paul Allen leased IBM a Personal Computer (PC) called MS-DOS (Microsoft Disk Operating System) for a one-time fee of $50,000\$50,000.
    • Gates Kept the copyright for MS-DOS
  • 1984: Steve Jobs and Steve Wozniak created Mac OS
    • Advertised on "More user-friendly"

5.2: Understanding Operating Systems

  • System software: Software that automatically runs to configure a computer (no human intervention)
  • Operating system (AKA Platform): A collection of computer programs that administer the hardware and software of a computer so that they work properly
    • Microsoft Windows, Mac OS, UNIX, Linux
  • Application software cannot run or be installed without a operating system.

5.3: Memory Management

  • Operating system coordinate: Computers memory

    • Cache, Random Access Memory (RAM), registers, and virtual memory
    • Disk Storage
  • CPU Cache: A small, very quick memory that stores copies of information and data from the most regularly-used parts of main memory

    • Helps decrease the time it takes to access memory.
  • Random Access Memory (RAM): Volatile memory

  • Disk Storage: Non-volatile memory

    • volatile memory stores data when a computer is on but erases it as soon as the computer is switched off, whereas non-volatile memory remains in a computer even after the system shuts off.

5.4: Memory Management Contd.

  • Registers: Small memory locations used to quicken the implementation of computer programs
    • Customization towards the device including wallpaper setting which is referred the process of registering.
  • Virtual Memory: Memory the OS uses to coordinate, track and efficiently allocate the use of CPU cache, registers, RAM and disk storage.
    • The messenger between volatile and non-volatile storage.

5.5: Disk Management

  • OS is responsible for saving information as efficiently as possible
    • Creates a table of contents of FAT (File Allocation Table)
  • Defragmentation: A program the reorganizes the hard drive
    • Note required for SSD
  • Hard Disk Drive (HDD)
    • Pros: More affordable, good for standard business procedures
    • Cons: more prone to damage
  • Solid State Drives (SSD)
    • Pros: N moving parts, more reliable
    • Cons: More expensive.

5.6: File Management

  • File manager are made up of Hierarchy of Directories, more commonly referred to as folders
    • Can be compared to a physical storage

5.7: Networks

  • Network: 2 or more computers connected together
  • Transmission control protocol and internet protocol (TCP/IP): A set of rules for transferring information from one computer to another
    • Transfers info by breaking up files into packates
  • The internet is the world's largest network

5.8: Device Drivers

  • Device Driver: Allows the OS to communicate with peripheral devices
  • Modern OS have plug-and-play capability
  • 1996: USB developed and considered industry standard

5.9: embedded Operating Systems

  • Embedded Operating System: OS installed on devices and appliances that rely on computing
    • Ex; Cash registers, automatic teller machines (ATM), microwaves, and specialized handled devices
    • Embedded OS cannot be modified in most cases
    • Embedded OS used on most cell pones
      • Google, Android, and iPhone

5.10: Mac or PC?

  • The answer is baed on the needs of the business
  • Ask yourself: Which one are your end-users comfortable or have experiencing using? Which one gives you a clear competitive advantage?

5.11: Major Operating Systems

  • Microsoft Windows: Windows 10
    • Windows 11 available for download
  • Mac Operating System (AKA Mac OS)
    • Version 14: Sonoma
  • Linux: An open-source OS that can be modified, used, and redistributed by anyone freely
    • Created by Linux Torvalds
  • UNIX: Popular for large processing applications like credit card transactions and approvals.

5.12: Open-Source OS

  • Proprietary software vs. open-source
    • Why doesn't everyone use open-source
  • Diffusion: A product or software is widely accepted
]]>
CIS105: Computer Applications & Information Systems Lect. 5

Chapter 5: Operating System

5.1: Operating System Fundamentals

  • 1980: Bill Gates and Paul Allen leased IBM a Personal Computer (PC) called MS-DOS (Microsoft Disk Operating System) for a one-time fee of $50,000\$50,000.
    • Gates Kept the copyright for MS-DOS
  • 1984: Steve Jobs and Steve Wozniak created Mac OS
    • Advertised on "More user-friendly"

5.2: Understanding Operating Systems

  • System software: Software that automatically runs to configure a computer (no human intervention)
  • Operating system (AKA Platform): A collection of computer programs that administer the hardware and software of a computer so that they work properly
    • Microsoft Windows, Mac OS, UNIX, Linux
  • Application software cannot run or be installed without a operating system.

5.3: Memory Management

  • Operating system coordinate: Computers memory

    • Cache, Random Access Memory (RAM), registers, and virtual memory
    • Disk Storage
  • CPU Cache: A small, very quick memory that stores copies of information and data from the most regularly-used parts of main memory

    • Helps decrease the time it takes to access memory.
  • Random Access Memory (RAM): Volatile memory

  • Disk Storage: Non-volatile memory

    • volatile memory stores data when a computer is on but erases it as soon as the computer is switched off, whereas non-volatile memory remains in a computer even after the system shuts off.

5.4: Memory Management Contd.

  • Registers: Small memory locations used to quicken the implementation of computer programs
    • Customization towards the device including wallpaper setting which is referred the process of registering.
  • Virtual Memory: Memory the OS uses to coordinate, track and efficiently allocate the use of CPU cache, registers, RAM and disk storage.
    • The messenger between volatile and non-volatile storage.

5.5: Disk Management

  • OS is responsible for saving information as efficiently as possible
    • Creates a table of contents of FAT (File Allocation Table)
  • Defragmentation: A program the reorganizes the hard drive
    • Note required for SSD
  • Hard Disk Drive (HDD)
    • Pros: More affordable, good for standard business procedures
    • Cons: more prone to damage
  • Solid State Drives (SSD)
    • Pros: N moving parts, more reliable
    • Cons: More expensive.

5.6: File Management

  • File manager are made up of Hierarchy of Directories, more commonly referred to as folders
    • Can be compared to a physical storage

5.7: Networks

  • Network: 2 or more computers connected together
  • Transmission control protocol and internet protocol (TCP/IP): A set of rules for transferring information from one computer to another
    • Transfers info by breaking up files into packates
  • The internet is the world's largest network

5.8: Device Drivers

  • Device Driver: Allows the OS to communicate with peripheral devices
  • Modern OS have plug-and-play capability
  • 1996: USB developed and considered industry standard

5.9: embedded Operating Systems

  • Embedded Operating System: OS installed on devices and appliances that rely on computing
    • Ex; Cash registers, automatic teller machines (ATM), microwaves, and specialized handled devices
    • Embedded OS cannot be modified in most cases
    • Embedded OS used on most cell pones
      • Google, Android, and iPhone

5.10: Mac or PC?

  • The answer is baed on the needs of the business
  • Ask yourself: Which one are your end-users comfortable or have experiencing using? Which one gives you a clear competitive advantage?

5.11: Major Operating Systems

  • Microsoft Windows: Windows 10
    • Windows 11 available for download
  • Mac Operating System (AKA Mac OS)
    • Version 14: Sonoma
  • Linux: An open-source OS that can be modified, used, and redistributed by anyone freely
    • Created by Linux Torvalds
  • UNIX: Popular for large processing applications like credit card transactions and approvals.

5.12: Open-Source OS

  • Proprietary software vs. open-source
    • Why doesn't everyone use open-source
  • Diffusion: A product or software is widely accepted
]]>
<![CDATA[CIS105: Computer Applications & Information Systems Lect. 6 Pt. 1 ]]> https://note.toshiki.dev/academic/cis105/cis105-l6-pt1-lecture-note https://note.toshiki.dev/academic/cis105/cis105-l6-pt1-lecture-note Thu, 01 Jul 2021 00:00:00 GMT CIS105: Computer Applications & Information Systems Lect. 6 Pt. 1

Chapter 6: System Software

6.1: System Software Overview

System Software:

  • Enables the Operating System
  • Controls memory, input and output, and manages filing system
  • Runs essential processes automatically
  • Controls the physical hardware so that applications software can work
  • If your computer is running, your system software is working

6.2: Starting the Computer

What happens when you press the power button:

  • System searches for Basic Input/Output System (BIOS)
  • Firmware, locates computer hardware
  • SS loads the platform (OS) into the computer’s memory: Booting
  • Powering up the computer for the first time: Cold Boot
  • Restarting a computer: Warm Boot
  • Computer will ask for login and load your profile
  • Preferences, themes, styles, and types of resources set up by the user
  • Registry loads settings made by the user
  • Screen savers, appearance, and personalizations

6.3: Administering Application Software

  • When a user clicks on an application, the application info moves from the hard drive to RAM (Random Access Memory)
  • SS and OS make sure application software works correctly

6.4: Memory Management

  • Computer memory allocation can be compared to a farmer allocating water for crops
  • Virtual memory: The technique of breaking large files down from the hard drive into smaller, more manageable files that fit in RAM
  • Smaller files called Pages
  • If the pages exceed RAM storage, OS will store temporary copies of pages to hard drive
  • Swap Files: When pages exceed RAM storage, OS swaps pages between hard drive and RAM Ask yourself: Does your business need new computers or new computer parts?
  • New computer: $800-1500
  • Upgraded RAM: $50-$200
  • Upgraded Hard Drive:$40-$100

6.5: Interfacing and Utilities

SS in the form of an OS must serve as a translator for both the computer and end user

  • Monitor: displays and renders output an end user can understand
  • GUI
  • Icon: A small pictogram on the desktop that a user clicks with a mouse
  • Window: A GUI unto its own
  • Device Drivers: allow input and output devices to operate properly
  • The background displayed on the monitor is considered the desktop environment, or "desktop" for short
  • Active Window: the window that the user is currently using

6.6: File Management Systems

Based on a hierarchy of folders that contain computer files. File management systems are searchable and provide information on files:

  • File Name
  • File Creation Date
  • File Modification Date
  • Location of the file
  • Who created or modified a file
  • File size
  • In business, it is important to establish your file management system early

6.7: System Software Utilities

  • Tracks: concentric circular bands
  • Sectors: Tracks that are separated into wedges
  • Defragmentation: Organizes + and – charges to the innermost tracks of the disk to reduce the amount of time it takes the R/W arm to find the info

6.8: Antivirus Utilities

Antivirus Utilities: System software that identifies known viruses to block them from entering and infecting a computer system

  • Utilizes a database of known viruses to cross reference against each incoming file
  • Subscription service: Norton Antivirus and McAfee VirusScan

6.9: System Updates

  • To compensate for OS inadequacies, OS offer a system software utility called system update
  • Patches sent from Microsoft (or Mac) via the Internet to a user’s computer
]]>
CIS105: Computer Applications & Information Systems Lect. 6 Pt. 1

Chapter 6: System Software

6.1: System Software Overview

System Software:

  • Enables the Operating System
  • Controls memory, input and output, and manages filing system
  • Runs essential processes automatically
  • Controls the physical hardware so that applications software can work
  • If your computer is running, your system software is working

6.2: Starting the Computer

What happens when you press the power button:

  • System searches for Basic Input/Output System (BIOS)
  • Firmware, locates computer hardware
  • SS loads the platform (OS) into the computer’s memory: Booting
  • Powering up the computer for the first time: Cold Boot
  • Restarting a computer: Warm Boot
  • Computer will ask for login and load your profile
  • Preferences, themes, styles, and types of resources set up by the user
  • Registry loads settings made by the user
  • Screen savers, appearance, and personalizations

6.3: Administering Application Software

  • When a user clicks on an application, the application info moves from the hard drive to RAM (Random Access Memory)
  • SS and OS make sure application software works correctly

6.4: Memory Management

  • Computer memory allocation can be compared to a farmer allocating water for crops
  • Virtual memory: The technique of breaking large files down from the hard drive into smaller, more manageable files that fit in RAM
  • Smaller files called Pages
  • If the pages exceed RAM storage, OS will store temporary copies of pages to hard drive
  • Swap Files: When pages exceed RAM storage, OS swaps pages between hard drive and RAM Ask yourself: Does your business need new computers or new computer parts?
  • New computer: $800-1500
  • Upgraded RAM: $50-$200
  • Upgraded Hard Drive:$40-$100

6.5: Interfacing and Utilities

SS in the form of an OS must serve as a translator for both the computer and end user

  • Monitor: displays and renders output an end user can understand
  • GUI
  • Icon: A small pictogram on the desktop that a user clicks with a mouse
  • Window: A GUI unto its own
  • Device Drivers: allow input and output devices to operate properly
  • The background displayed on the monitor is considered the desktop environment, or "desktop" for short
  • Active Window: the window that the user is currently using

6.6: File Management Systems

Based on a hierarchy of folders that contain computer files. File management systems are searchable and provide information on files:

  • File Name
  • File Creation Date
  • File Modification Date
  • Location of the file
  • Who created or modified a file
  • File size
  • In business, it is important to establish your file management system early

6.7: System Software Utilities

  • Tracks: concentric circular bands
  • Sectors: Tracks that are separated into wedges
  • Defragmentation: Organizes + and – charges to the innermost tracks of the disk to reduce the amount of time it takes the R/W arm to find the info

6.8: Antivirus Utilities

Antivirus Utilities: System software that identifies known viruses to block them from entering and infecting a computer system

  • Utilizes a database of known viruses to cross reference against each incoming file
  • Subscription service: Norton Antivirus and McAfee VirusScan

6.9: System Updates

  • To compensate for OS inadequacies, OS offer a system software utility called system update
  • Patches sent from Microsoft (or Mac) via the Internet to a user’s computer
]]>
<![CDATA[CIS105: Computer Applications & Information Systems Lect. 6 Pt. 2 ]]> https://note.toshiki.dev/academic/cis105/cis105-l6-pt2-lecture-note https://note.toshiki.dev/academic/cis105/cis105-l6-pt2-lecture-note Thu, 01 Jul 2021 00:00:00 GMT CIS105: Computer Applications & Information Systems Lect. 6 Pt. 2

Chapter 6: Logical Functions

6.1: New Functions

  • AND: Checks whether all arguments are TRUE, and returns TRUE if all arguments are TRUE.

  • OR: Checks whether any of the arguments are TRUE, and returns TRUE or FALSE.

  • NOT: Changes TRUE to FALSE, or FALSE to TRUE.

  • IF: Checks whether a condition is met, and returns one value if TRUE, and another value if FALSE.

    • Nested IF: Using multiple IF statements in one functions to account for multiple conditions.
  • VLOOKUP: Looks for a value in a table or a range veryically

    • VLOOKUP What you want to look up, where you want to look for it, the column number in the range containing the value to return, return an approximate or exact match: Indicates as 1/TRUE, or 0/FALSE.
  • HLOOKUP: Looks for a value in a table or a range horizontally.

  • COUNTIF: Counts the number of cells within a range that meet the given condition.

    • =COUNTIF(Where do you want to look? What do you want to look for?)
  • SUMIF: Adds the cells specified by a given condition or criteria.

  • AVERAGEIF: s an Excel Statistical function, which calculates the average of a given range of cells by a specific criterion.

6.2: Comparison Operators

  • >: More than
  • <: Less than
  • >=: More than or equal to
  • <=: Less that or equal to

6.3: Reminder

  • Excel does not recognize tex
    • When searching for keywords, put keyword between "" delimiters.
]]>
CIS105: Computer Applications & Information Systems Lect. 6 Pt. 2

Chapter 6: Logical Functions

6.1: New Functions

  • AND: Checks whether all arguments are TRUE, and returns TRUE if all arguments are TRUE.

  • OR: Checks whether any of the arguments are TRUE, and returns TRUE or FALSE.

  • NOT: Changes TRUE to FALSE, or FALSE to TRUE.

  • IF: Checks whether a condition is met, and returns one value if TRUE, and another value if FALSE.

    • Nested IF: Using multiple IF statements in one functions to account for multiple conditions.
  • VLOOKUP: Looks for a value in a table or a range veryically

    • VLOOKUP What you want to look up, where you want to look for it, the column number in the range containing the value to return, return an approximate or exact match: Indicates as 1/TRUE, or 0/FALSE.
  • HLOOKUP: Looks for a value in a table or a range horizontally.

  • COUNTIF: Counts the number of cells within a range that meet the given condition.

    • =COUNTIF(Where do you want to look? What do you want to look for?)
  • SUMIF: Adds the cells specified by a given condition or criteria.

  • AVERAGEIF: s an Excel Statistical function, which calculates the average of a given range of cells by a specific criterion.

6.2: Comparison Operators

  • >: More than
  • <: Less than
  • >=: More than or equal to
  • <=: Less that or equal to

6.3: Reminder

  • Excel does not recognize tex
    • When searching for keywords, put keyword between "" delimiters.
]]>
<![CDATA[CIS105: Computer Applications & Information Systems Lect. 7 ]]> https://note.toshiki.dev/academic/cis105/cis105-l7-lecture-note https://note.toshiki.dev/academic/cis105/cis105-l7-lecture-note Thu, 01 Jul 2021 00:00:00 GMT CIS105: Computer Applications & Information Systems Lect. 7

Chapter 7: Green Business Computing

7.1: Green Business Computing

  • Burning fossil fules creates carbon dioxide which builds up and slows the escape of heat into space, called the "greenhouse effect".
  • NASA predicts Earth's surface temperature will increase by 2.5 to 10.4 Fahrenheit by the year 2100. The concern is that human societies and natural ecosystems may not adapt quickly enough.
  • The National Center for Atmospheric Research (NCAR) in charge of creating and maintaining climate computer models that are used to predict weather admit they are flawed and unreliable.
  • Who's right, ASA or NCAR?

7.2: Climate Change

  • Whether global warming exists is a discussion that requires critical thoughtfullnesswith a minimum of passion.
  • It is virtually impossible to not come across terminologies like "green" or challenges, and potential sustainable solutions have gained traction and must be dealt with.
  • Regardless of differing views, climate change has gained diffusion and acceptance as an acknowledged problem that will drive business for many years to come. Environmental responsibility and global governance is simply the right things to do.

7.3: IT Challenges and Opportunities

  • Chief technology officers (in charge of all business computing assets) meed to be concerned with overall energy costs associated with computing systems.
  • Electronic Product Environmental Assessment Tool (EPEAT)
    • Started by the Environmental Protection Agency in 2006.
    • Managed by the Green Electronics Council (GEC)
    • Easy to use online tool

7.4: EPEAT Criteria

EPEAT evaluates electronic products relative to 51 environmental criteria, 23 required and 28 optional. Computer manufacturers that meet a certain criteria are awarded a gold, silver, or bronze star allowing the consumer to differentiate products.

  • Reduction or elimination of environmentally sensitive materials. Computers contain potentially harmful chemicals like cadmium, mercury, and chromium. EPEAT Encourages manufacturers to reduce or eliminate them altogether.

  • Materials Selection informs the consumer of the percentage of recycled plastic and offers a declaration of percentage of renewable/bio-based plastic material content.

  • Design for End of Life informs consumers about special handling needs for disposing of their product when it no longer useful.

  • Product Longevity/Life Cycle Extension encourages manufacturers to make extended warranties available so their product lasts longer or available to be upgraded.

  • End of Life Management asks manufacturers to take their product back at the end of the product’s life, at no cost to the consumer.

  • Corporate Performance means a manufacturer demonstrates a sound corporate environmental policy throughout their business.

  • Packaging criteria requires manufacturers to reduce or eliminate intentionally added toxins in packaging.

  • Energy Conservation asks manufacturers to adopt the government’s Energy Star® specifications.

EPEAT criteria seems difficult and expensive for a gold star, so why would manufacturers be willing to comply? Had you ever heard of EPEAT? Did you base your last computer purchase on EPEAT criteria? If you were aware of EPEAT, would you pay more just to be green? What if your business pays significantly more for EPEAT computers and your competitor doesn’t, did they get an edge?

7.5: Energy Star® Specifications

  • Started in 1772 as a voluntary labeling program to identify and promote energy efficient products.

  • Energy Star® claims that if every computer in the United States met Energy Star® requirements, the savings in energy costs alone will grow to about $2 billion each year and greenhouse gas emissions would be reduced by the the equivalent of that from 2 million cars.

  • In many instances, Energy Star® computers are more expensive to purchase but are far more efficient and cost effective in the long run

7.6: The Green PC

A Green PC is a personal computer that is environmentally friendly and includes the following:

  • Energy-efficient power supplies

  • Includes processors that consume minimum amounts of electricity

  • Attempt to do away with or minimize environmentally harmful components

  • Makes use of aluminum or plastic parts from recycled materials

The most important factor in a Green PC is energy efficiency

7.7: Modes

  • Active Use: The computer is on and being use

  • Sleep Mode: Low power after a designated period of time

  • Standby Mode (Off): Turns off after designated period of time

7.8: Green Business Computing Plan

Based on the idea that businesses can be environmentally friendly, more profitable, and socially responsible.

  • Organizational policies and procedures

  • Best Practice considerations

  • Long term, sustainable considerations

  • Reduction of power usage and paper consumption

  • Recycling policies and procedures

  • Used computer software and hardware disposal

  • EPEAT and Energy Star® compliance

  • Green PC purchasing recommendations

]]>
CIS105: Computer Applications & Information Systems Lect. 7

Chapter 7: Green Business Computing

7.1: Green Business Computing

  • Burning fossil fules creates carbon dioxide which builds up and slows the escape of heat into space, called the "greenhouse effect".
  • NASA predicts Earth's surface temperature will increase by 2.5 to 10.4 Fahrenheit by the year 2100. The concern is that human societies and natural ecosystems may not adapt quickly enough.
  • The National Center for Atmospheric Research (NCAR) in charge of creating and maintaining climate computer models that are used to predict weather admit they are flawed and unreliable.
  • Who's right, ASA or NCAR?

7.2: Climate Change

  • Whether global warming exists is a discussion that requires critical thoughtfullnesswith a minimum of passion.
  • It is virtually impossible to not come across terminologies like "green" or challenges, and potential sustainable solutions have gained traction and must be dealt with.
  • Regardless of differing views, climate change has gained diffusion and acceptance as an acknowledged problem that will drive business for many years to come. Environmental responsibility and global governance is simply the right things to do.

7.3: IT Challenges and Opportunities

  • Chief technology officers (in charge of all business computing assets) meed to be concerned with overall energy costs associated with computing systems.
  • Electronic Product Environmental Assessment Tool (EPEAT)
    • Started by the Environmental Protection Agency in 2006.
    • Managed by the Green Electronics Council (GEC)
    • Easy to use online tool

7.4: EPEAT Criteria

EPEAT evaluates electronic products relative to 51 environmental criteria, 23 required and 28 optional. Computer manufacturers that meet a certain criteria are awarded a gold, silver, or bronze star allowing the consumer to differentiate products.

  • Reduction or elimination of environmentally sensitive materials. Computers contain potentially harmful chemicals like cadmium, mercury, and chromium. EPEAT Encourages manufacturers to reduce or eliminate them altogether.

  • Materials Selection informs the consumer of the percentage of recycled plastic and offers a declaration of percentage of renewable/bio-based plastic material content.

  • Design for End of Life informs consumers about special handling needs for disposing of their product when it no longer useful.

  • Product Longevity/Life Cycle Extension encourages manufacturers to make extended warranties available so their product lasts longer or available to be upgraded.

  • End of Life Management asks manufacturers to take their product back at the end of the product’s life, at no cost to the consumer.

  • Corporate Performance means a manufacturer demonstrates a sound corporate environmental policy throughout their business.

  • Packaging criteria requires manufacturers to reduce or eliminate intentionally added toxins in packaging.

  • Energy Conservation asks manufacturers to adopt the government’s Energy Star® specifications.

EPEAT criteria seems difficult and expensive for a gold star, so why would manufacturers be willing to comply? Had you ever heard of EPEAT? Did you base your last computer purchase on EPEAT criteria? If you were aware of EPEAT, would you pay more just to be green? What if your business pays significantly more for EPEAT computers and your competitor doesn’t, did they get an edge?

7.5: Energy Star® Specifications

  • Started in 1772 as a voluntary labeling program to identify and promote energy efficient products.

  • Energy Star® claims that if every computer in the United States met Energy Star® requirements, the savings in energy costs alone will grow to about $2 billion each year and greenhouse gas emissions would be reduced by the the equivalent of that from 2 million cars.

  • In many instances, Energy Star® computers are more expensive to purchase but are far more efficient and cost effective in the long run

7.6: The Green PC

A Green PC is a personal computer that is environmentally friendly and includes the following:

  • Energy-efficient power supplies

  • Includes processors that consume minimum amounts of electricity

  • Attempt to do away with or minimize environmentally harmful components

  • Makes use of aluminum or plastic parts from recycled materials

The most important factor in a Green PC is energy efficiency

7.7: Modes

  • Active Use: The computer is on and being use

  • Sleep Mode: Low power after a designated period of time

  • Standby Mode (Off): Turns off after designated period of time

7.8: Green Business Computing Plan

Based on the idea that businesses can be environmentally friendly, more profitable, and socially responsible.

  • Organizational policies and procedures

  • Best Practice considerations

  • Long term, sustainable considerations

  • Reduction of power usage and paper consumption

  • Recycling policies and procedures

  • Used computer software and hardware disposal

  • EPEAT and Energy Star® compliance

  • Green PC purchasing recommendations

]]>
<![CDATA[CIS105: Computer Applications & Information Systems Lect. 8 ]]> https://note.toshiki.dev/academic/cis105/cis105-l8-lecture-note https://note.toshiki.dev/academic/cis105/cis105-l8-lecture-note Thu, 01 Jul 2021 00:00:00 GMT CIS105: Computer Applications & Information Systems Lect. 8

Chapter 8: Computer Networks

8.1: Computer Networks

  • Two or more computers connected together to share resources like:
  • Folders and files
  • Software
  • Hardware
  • Scanners, Printers, Webcams, etc. Consider a network made up of three computers (Clients) connected to one computer called a Server. The server is connected to a printer and a scanner (peripheral devices) enabling all three clients to use them. Any device connected to a network is called a node.

8.2: Building a Computer Network

All networks require four basic components

  1. Network Interface Controller Card (NIC): Plugged into the motherboard to interface and connect with other computers.
  2. Protocol: TCP/IP controls how data and information is shared between computers.
  3. Cables: Cables connect servers to clients which can sometimes be replaced through wireless connections.
  4. Hub: Typically, the central location of a network (server) that serves to run the network smoothly

8.3: Network Protocols

Provides a common language and rules for communication between computers. A protocol is a convention or standard that controls or allows communication and data transfer between two computers.

  • Transmission Control Protocol / Internet Protocol (TCP/IP): When sending a file from one computer to another, the file is broken down into smaller files called “packets”. The packets arrive at the receiving computer and must be reassembled correctly to guarantee the receiving computer gets a file that will work (not corrupted).
  • User Datagram Packets: Break large files into packets, but unlike TCP/IP, allows a user to use the incoming file.

8.4: Network Operating Systems

A Network Operating System (NOS) is similar to a stand-alone platform but responsible for much more:

  • Automatic hardware detection. The NOS recognizes it when it becomes part of the network.
  • Supports multi-processing which allows several processes to occur at one time.
  • Recognizes who is using the network.
  • Provides security

8.5: Network Administrator

  • Responsible for smooth network operations
  • Network performance
  • Implementation of new nodes and users
  • Strong business background

8.6: Network Topology

Refers to the mapping of a physical network and logical interconnections between nodes. Basically, the way a network is arranged and laid out.

  • Bus Topology: Sometimes called a linear bus topology where the network’s nodes are connected to a common linear backbone with tw endpoints. If the backbone fails, the whole network fails.
  • Star Topology: One central server in which clients connect in a spoke- like fashion, or star. If the server fails, the network fails. (Most common topology)
  • Ring Topology: Data is transferred between computers in a circular manner.

8.7: Types of Computer Networks

  • Local Area Network (LAN): A small network typically confined by a single building. Often used by smaller businesses.
  • Campus Area Network (CAN): Connects two or more LANs which are located on universities or large businesses.
  • Metropolitan Area Network (MAN): A computer network that connects CANs and LANs into a larger network like a city.
  • Wide Area Network (WAN): Connects LANs, CANs, and MANs and can cover an entire country
  • Peer to Peer (P2P): Generally, connect computers to each other.
  • Internet: The world’s largest network interconnecting public, private, commercial, and governmental networks. Network Security Starts with a solid understanding of network threats. Network administrators must adopt policies which define rules for network access.
  • Passwords: A secret word or combination of keyboard characters typed in by the user to authenticate their identity to a network and gain appropriate access.
  • Strong Passwords: Same as passwords, but requires a user to use upper case characters, lower case characters, numbers, and special characters.
  • Passphrase: Same as a Strong Password, but a phrase that is memorable.

8.8: Network Security

  • Web Browsing on a Network: Part of network security includes policies and procedures regarding employee’s web browsing. Should a business let employees browse on the Web?
  • Email / Instant Messaging: On a business network, consider that all email and instant message is recorded and saved, therefore, policies and procedures must be in place regarding appropriate usage.
  • Permissions: Network access is called “permissions”, which grants and denies access to a network depending on the user.
  • Firewall: Hardware and software on a proxy server that determines who is allowed on a network, and who is not.

8.9: Green Business Computing Plan

Based on the idea that businesses can be environmentally friendly, more profitable, and socially responsible.

  • Organizational policies and procedures
  • Best Practice considerations
  • Long term, sustainable considerations
  • Reduction of power usage and paper consumption
  • Recycling policies and procedures
  • Used computer software and hardware disposal
  • EPEAT and Energy Star® compliance
  • Green PC purchasing recommendations
]]>
CIS105: Computer Applications & Information Systems Lect. 8

Chapter 8: Computer Networks

8.1: Computer Networks

  • Two or more computers connected together to share resources like:
  • Folders and files
  • Software
  • Hardware
  • Scanners, Printers, Webcams, etc. Consider a network made up of three computers (Clients) connected to one computer called a Server. The server is connected to a printer and a scanner (peripheral devices) enabling all three clients to use them. Any device connected to a network is called a node.

8.2: Building a Computer Network

All networks require four basic components

  1. Network Interface Controller Card (NIC): Plugged into the motherboard to interface and connect with other computers.
  2. Protocol: TCP/IP controls how data and information is shared between computers.
  3. Cables: Cables connect servers to clients which can sometimes be replaced through wireless connections.
  4. Hub: Typically, the central location of a network (server) that serves to run the network smoothly

8.3: Network Protocols

Provides a common language and rules for communication between computers. A protocol is a convention or standard that controls or allows communication and data transfer between two computers.

  • Transmission Control Protocol / Internet Protocol (TCP/IP): When sending a file from one computer to another, the file is broken down into smaller files called “packets”. The packets arrive at the receiving computer and must be reassembled correctly to guarantee the receiving computer gets a file that will work (not corrupted).
  • User Datagram Packets: Break large files into packets, but unlike TCP/IP, allows a user to use the incoming file.

8.4: Network Operating Systems

A Network Operating System (NOS) is similar to a stand-alone platform but responsible for much more:

  • Automatic hardware detection. The NOS recognizes it when it becomes part of the network.
  • Supports multi-processing which allows several processes to occur at one time.
  • Recognizes who is using the network.
  • Provides security

8.5: Network Administrator

  • Responsible for smooth network operations
  • Network performance
  • Implementation of new nodes and users
  • Strong business background

8.6: Network Topology

Refers to the mapping of a physical network and logical interconnections between nodes. Basically, the way a network is arranged and laid out.

  • Bus Topology: Sometimes called a linear bus topology where the network’s nodes are connected to a common linear backbone with tw endpoints. If the backbone fails, the whole network fails.
  • Star Topology: One central server in which clients connect in a spoke- like fashion, or star. If the server fails, the network fails. (Most common topology)
  • Ring Topology: Data is transferred between computers in a circular manner.

8.7: Types of Computer Networks

  • Local Area Network (LAN): A small network typically confined by a single building. Often used by smaller businesses.
  • Campus Area Network (CAN): Connects two or more LANs which are located on universities or large businesses.
  • Metropolitan Area Network (MAN): A computer network that connects CANs and LANs into a larger network like a city.
  • Wide Area Network (WAN): Connects LANs, CANs, and MANs and can cover an entire country
  • Peer to Peer (P2P): Generally, connect computers to each other.
  • Internet: The world’s largest network interconnecting public, private, commercial, and governmental networks. Network Security Starts with a solid understanding of network threats. Network administrators must adopt policies which define rules for network access.
  • Passwords: A secret word or combination of keyboard characters typed in by the user to authenticate their identity to a network and gain appropriate access.
  • Strong Passwords: Same as passwords, but requires a user to use upper case characters, lower case characters, numbers, and special characters.
  • Passphrase: Same as a Strong Password, but a phrase that is memorable.

8.8: Network Security

  • Web Browsing on a Network: Part of network security includes policies and procedures regarding employee’s web browsing. Should a business let employees browse on the Web?
  • Email / Instant Messaging: On a business network, consider that all email and instant message is recorded and saved, therefore, policies and procedures must be in place regarding appropriate usage.
  • Permissions: Network access is called “permissions”, which grants and denies access to a network depending on the user.
  • Firewall: Hardware and software on a proxy server that determines who is allowed on a network, and who is not.

8.9: Green Business Computing Plan

Based on the idea that businesses can be environmentally friendly, more profitable, and socially responsible.

  • Organizational policies and procedures
  • Best Practice considerations
  • Long term, sustainable considerations
  • Reduction of power usage and paper consumption
  • Recycling policies and procedures
  • Used computer software and hardware disposal
  • EPEAT and Energy Star® compliance
  • Green PC purchasing recommendations
]]>
<![CDATA[CIS105: Computer Applications & Information Systems Lect. 9 ]]> https://note.toshiki.dev/academic/cis105/cis105-l9-lecture-note https://note.toshiki.dev/academic/cis105/cis105-l9-lecture-note Thu, 01 Jul 2021 00:00:00 GMT CIS105: Computer Applications & Information Systems Lect. 9

Chapter 9: Internet

9.1: Internet History

  • 1969: University of California Los Angeles (UCLA) created the Advanced Research Project Agency Network (ARPANET)
  • 1989: Hypertext Transfer Protocol (HTTP) / World Wide Web (WWW)
  • 1993: Hypertext Markup Langauge (HTML)

9.2: Internet and WWW Structure

  • he internet is a network called the Client/Server Model
  • The browser application software interprets HTML and HTTP to create web pages
  • Everything on the internet lives somewhere physically; the trick is using computer addresses to send info from one place to another

9.3: Internet Addresses

  • Internet Protocol Address (IP): An address system used to identify and communicate through the network
  • Uniform Resource Locators (URLs)
    • https://asu.edu
    • https: refers to standard protocol
    • www: refers to the world wide web
    • Canvas.asu: domain name
    • .edu: a top-level domain code or extension

9.4/9.5: Websites/Browsers

  • Website: A collection of web pages on a server that exists on the web that can be requested by a client and displayed with a browser
  • Hyperlink: Clickable navigation element
  • Browser: An application software that provides an interface for the WWW
  • Aspects of a good website:
    • Content
    • Interactivity
    • Design

9.6: Browser Features

  • Common Browser Features
    • Bookmarks: AKA favorites
    • Caching: Just like a CPU cache on the internet
    • Cookies: Text files used to track info about users
    • Graphics File (GIF, JPEG): Images and videos
    • Javascript: A programming language
      • Used to make websites dynamics; Ex: Countdown timer
  • Browser Considerations:
    • Security
    • Popup Blockers
    • Usability

9.7: Internet Service Providers (ISP)

  • Connectivity: When one computer connects to another and shares info & resources
  • Internet Service Providers (ISP)
    • Dial-up & Digital Subscriber Line (DSL)
    • Broadband Internet Access
    • Web Hosting

9.8: Search Engines

  • Search engine: A website that lets a user type in specific key words or phrases and then return a list of hyperlinks that best match the search criteria
    • Google, Bing, Yahoo
    • Directory searches
    • Metasearch Engines
      • Ex: Dogpile

9.9: E-Commerce

  • Electronic Commerce (E-Commerce): The distribution, buying, selling, advertising, and marketing of goods and services over the web
    • Business-to-Business (B2B)
    • Business-to-Consumer (B2C)
    • Consumer-to-Consumer (C2C)
  • The rules of business still apply to online environments

9.10: Security

  • Malware: Software designed to damage a computer's system without the owner's knowledge
    • Virus
    • Worms
    • Trojan Horse
    • Spyware
    • Adware

9.11/9.12: Email/Email Security

  • Email: "A store and forward" system of composing, sending, storing, and receiving message over electronic communication systems.
  • Never send an email you wouldn't be willing to say in public
  • Phishing: An email that looks official but is malicious in nature
  • Spam: Unwanted mail
]]>
CIS105: Computer Applications & Information Systems Lect. 9

Chapter 9: Internet

9.1: Internet History

  • 1969: University of California Los Angeles (UCLA) created the Advanced Research Project Agency Network (ARPANET)
  • 1989: Hypertext Transfer Protocol (HTTP) / World Wide Web (WWW)
  • 1993: Hypertext Markup Langauge (HTML)

9.2: Internet and WWW Structure

  • he internet is a network called the Client/Server Model
  • The browser application software interprets HTML and HTTP to create web pages
  • Everything on the internet lives somewhere physically; the trick is using computer addresses to send info from one place to another

9.3: Internet Addresses

  • Internet Protocol Address (IP): An address system used to identify and communicate through the network
  • Uniform Resource Locators (URLs)
    • https://asu.edu
    • https: refers to standard protocol
    • www: refers to the world wide web
    • Canvas.asu: domain name
    • .edu: a top-level domain code or extension

9.4/9.5: Websites/Browsers

  • Website: A collection of web pages on a server that exists on the web that can be requested by a client and displayed with a browser
  • Hyperlink: Clickable navigation element
  • Browser: An application software that provides an interface for the WWW
  • Aspects of a good website:
    • Content
    • Interactivity
    • Design

9.6: Browser Features

  • Common Browser Features
    • Bookmarks: AKA favorites
    • Caching: Just like a CPU cache on the internet
    • Cookies: Text files used to track info about users
    • Graphics File (GIF, JPEG): Images and videos
    • Javascript: A programming language
      • Used to make websites dynamics; Ex: Countdown timer
  • Browser Considerations:
    • Security
    • Popup Blockers
    • Usability

9.7: Internet Service Providers (ISP)

  • Connectivity: When one computer connects to another and shares info & resources
  • Internet Service Providers (ISP)
    • Dial-up & Digital Subscriber Line (DSL)
    • Broadband Internet Access
    • Web Hosting

9.8: Search Engines

  • Search engine: A website that lets a user type in specific key words or phrases and then return a list of hyperlinks that best match the search criteria
    • Google, Bing, Yahoo
    • Directory searches
    • Metasearch Engines
      • Ex: Dogpile

9.9: E-Commerce

  • Electronic Commerce (E-Commerce): The distribution, buying, selling, advertising, and marketing of goods and services over the web
    • Business-to-Business (B2B)
    • Business-to-Consumer (B2C)
    • Consumer-to-Consumer (C2C)
  • The rules of business still apply to online environments

9.10: Security

  • Malware: Software designed to damage a computer's system without the owner's knowledge
    • Virus
    • Worms
    • Trojan Horse
    • Spyware
    • Adware

9.11/9.12: Email/Email Security

  • Email: "A store and forward" system of composing, sending, storing, and receiving message over electronic communication systems.
  • Never send an email you wouldn't be willing to say in public
  • Phishing: An email that looks official but is malicious in nature
  • Spam: Unwanted mail
]]>
<![CDATA[CIS105: Computer Appls&Info Technology (2024 Spring) ]]> https://note.toshiki.dev/academic/cis105/ https://note.toshiki.dev/academic/cis105/ Thu, 01 Jul 2021 00:00:00 GMT CIS105: Computer Appls&Info Technology (2024 Spring)

Courseload Overview

REQUIRED

TEXTBOOKS:

Week 1


Week 2

 

 

Week 3


Week 4

 

Week 5

 

Week 6

 

Exam 1: February 22nd - 23rd

 

Week 7


Week 8

 

Mar 4th - 10th

SPRING BREAK

Week 9

 

Week 10

 

Week 11

 

 Exam 2

Week 12

 

Week 13

 

 
 
  • Lecture - Thur, Apr 18th
  • Final Exam Review
 Final Exam
]]>
CIS105: Computer Appls&Info Technology (2024 Spring)

Courseload Overview

REQUIRED

TEXTBOOKS:

Week 1


Week 2

 

 

Week 3


Week 4

 

Week 5

 

Week 6

 

Exam 1: February 22nd - 23rd

 

Week 7


Week 8

 

Mar 4th - 10th

SPRING BREAK

Week 9

 

Week 10

 

Week 11

 

 Exam 2

Week 12

 

Week 13

 

 
 
  • Lecture - Thur, Apr 18th
  • Final Exam Review
 Final Exam
]]>
<![CDATA[Welcome to Literature ]]> https://note.toshiki.dev/academic/literature/ https://note.toshiki.dev/academic/literature/ Thu, 01 Jul 2021 00:00:00 GMT Welcome to Literature ]]> Welcome to Literature ]]> <![CDATA[Patterns of Organization and Methods of Development]]> https://note.toshiki.dev/academic/literature/writing/methods-of-development https://note.toshiki.dev/academic/literature/writing/methods-of-development Thu, 01 Jul 2021 00:00:00 GMT Patterns of Organization and Methods of Development

Patterns of organization can help your readers follow the ideas within your essay and your paragraphs, but they can also work as methods of development to help you recognize and further develop ideas and relationships in your writing. Here are some strategies that can help you with both organization and development in your essays.

Major Patterns of Organization

A fruit pie.

Read the following sentences:

  • Now take the pie out of the oven and let it cool on the stovetop.
  • Mix the dry ingredients with the liquid ingredients.
  • Set the pie crust aside while you make the filling.

How did it feel to read the above list? A bit confusing, I would guess. That’s because the steps for making a pie were not well organized, and the steps don’t include enough detail for us to know exactly what we should do. (Like what are the dry and liquid ingredients?) We all know that starting instructions from the beginning and giving each detailed step in the order it should happen is vital to having a good outcome, in this case a yummy pie! But it’s not always so simple to know how to organize or develop ideas, and sometimes there’s more than one way, which complicates things even further.

First, let’s take a look at a couple of ways to think about organization.

General to Specific or Specific to General

It might be useful to think about organizing your topic like a triangle:

Two triangles. The first is an inverted pyramid for General to Specific, the second is a pyramid for Specific to General.

The first triangle represents starting with the most general, big picture information first, moving then to more detailed and often more personal information later in the paper. The second triangle represents an organizational structure that starts with the specific, small scale information first and then moves to the more global, big picture stuff.

For example, if your topic is traffic in Vancouver, British Columbia, an essay that uses the general-to-specific organizational structure might begin this way:

Many people consider Vancouver, British Columbia, to be a relaxed place to live. They would be shocked to know how bad the traffic is traveling major arteries into the city and even driving around the city itself.

An essay that uses the specific-to-general structure might start like this:

Transit is crowded, parking is expensive, and vehicles stop and go through the main streets of the city of Vancouver, British Columbia, and that is just once travelers brave the crowded arteries to enter the city; Vancouver’s traffic problem does not lend itself to the relaxed atmosphere many believe the city to have.

What’s the difference between these two introductions? And how might they appeal to the intended audience for this essay in different ways? The first introduction is looking at the big picture of the problem and mentions pollution’s impact on all citizens in Portland, while the second introduction focuses on one specific family. The first helps readers see how vast the problem really is, and the second helps connect readers to a real family, making an emotional appeal from the very beginning. Neither introduction is necessarily better. You’ll choose one over the other based on the kind of tone you’d like to create and how you’d like to affect your audience. It’s completely up to you to make this decision.

Does the Triangle Mean the Essay Keeps Getting More Specific or More Broad until the Very End?

The triangle is kind of a general guide, meaning you’re allowed to move around within it all you want. For example, it’s possible that each of your paragraphs will be its own triangle, starting with the general or specific and moving out or in. However, if you begin very broadly, it might be effective to end your essay in a more specific, personal way. And if you begin with a personal story, consider ending your essay by touching on the global impact and importance of your topic.

Are There Other Ways to Think about Organizing My Ideas?

Yes! Rather than thinking about which of your ideas are most specific or personal or which are more broad or universal, you might consider one of the following ways of organizing your ideas:

  • Most important information first (consider what you want readers to focus on first)
  • Chronological order (the order in time that events take place)
  • Compare and contrast (ideas are organized together because of their relationship to each other)

The section on Methods of Development, below, offers more detail about some of these organizational patterns, along with some others.

Choose one of the following topics, and practice writing a few opening sentences like we did above, once using the general-to-specific format and once using the specific-to-general. Which do you like better? What audience would be attracted to which one? Share with peers to see how others tackled this challenge. How would you rewrite their sentences? Why? Discuss your changes and listen to how your peers have revised your sentences. Taking in other people’s ideas will help you see new ways to approach your own writing and thinking.
Topics:

  • Facing fears
  • Safety in sports
  • Community policing
  • Educating prisoners
  • Sex education

Methods of Development

The methods of development covered here are best used as ways to look at what’s already happening in your draft and to consider how you might emphasize or expand on any existing patterns. You might already be familiar with some of these patterns because teachers will sometimes assign them as the purpose for writing an essay. For example, you might have been asked to write a cause-and-effect essay or a comparison-and-contrast essay.

It’s important to emphasize here that patterns of organization or methods of developing content usually happen naturally as a consequence of the way the writer engages with and organizes information while writing. That is to say, most writers don’t sit down and say, “I think I’ll write a cause-and-effect essay today.” Instead, a writer might be more likely to be interested in a topic, say, the state of drinking water in the local community, and as the writer begins to explore the topic, certain cause-and-effect relationships between environmental pollutants and the community water supply may begin to emerge.

So if these patterns just occur naturally in writing, what’s the use in knowing about them? Well, sometimes you might be revising a draft and notice that some of your paragraphs are a bit underdeveloped. Maybe they lack a clear topic, or maybe they lack support. In either case, you can look to these common methods of development to find ways to sharpen those vague topics or to add support where needed. Do you have a clear cause statement somewhere but you haven’t explored the effects? Are you lacking detail somewhere where a narrative story or historical chronology can help build reader interest and add support? Are you struggling to define an idea that might benefit from some comparison or contrast? Read on to consider some of the ways that these strategies can help you in revision.

Cause and Effect (or Effect and Cause)

Do you see a potential cause-and-effect relationship developing in your draft? The cause-and-effect pattern may be used to identify one or more causes followed by one or more effects or results. Or you may reverse this sequence and describe effects first and then the cause or causes. For example, the causes of water pollution might be followed by its effects on both humans and animals. You may use obvious transitions to clarify cause and effect, such as “What are the results? Here are some of them…” or you might simply use the words cause, effect, and result, to cue the reader about your about the relationships that you’re establishing.

Problem-Solution

At some point does your essay explore a problem or suggest a solution? The problem-solution pattern is commonly used in identifying something that’s wrong and in contemplating what might be done to remedy the situation. There are probably more ways to organize a problem-solution approach, but but here are three possibilities:

  • Describe the problem, followed by the solution.
  • Propose the solution first and then describe the problems that motivated it.
  • Or a problem may be followed by several solutions, one of which is selected as the best.

When the solution is stated at the end of the paper, the pattern is sometimes called the delayed proposal. For a hostile audience, it may be effective to describe the problem, show why other solutions do not work, and finally suggest the favored solution. You can emphasize the words problem and solution to signal these sections of your paper for your reader.

Chronology or Narrative

Do you need to develop support for a topic where telling a story can illustrate some important concept for your readers? Material arranged chronologically is explained as it occurs in time. A chronological or narrative method of development might help you find a way to add both interest and content to your essay. Material arranged chronologically is explained as it occurs in time. This pattern may be used to establish what has happened. Chronology or narrative can be a great way to introduce your essay by providing a background or history behind your topic. Or you may want to tell a story to develop one or more points in the body of your essay. You can use transitional words like then, next, and finally to make the parts of the chronology clear.

Comparison and Contrast

Are you trying to define something? Do you need your readers to understand what something is and what it is not? The comparison-and-contrast method of development is particularly useful in extending a definition, or anywhere you need to show how a subject is like or unlike another subject. For example, the statement is often made that drug abuse is a medical problem instead of a criminal justice issue. An author might attempt to prove this point by comparing drug addiction to AIDS, cancer, or heart disease to redefine the term “addiction” as a medical problem. A statement in opposition to this idea could just as easily establish contrast by explaining all the ways that addiction is different from what we traditionally understand as an illness. In seeking to establish comparison or contrast in your writing, some words or terms that might be useful are by contrast, in comparison, while, some, and others.

Summary

These four methods of development—cause and effect, problem-solution, chronology or narrative, and comparison and contrast—are just a few ways to organize and develop ideas and content in your essays. It’s important to note that they should not be a starting point for writers who want to write something authentic—something that they care deeply about. Instead, they can be a great way to help you look for what’s already happening with your topic or in a draft, to help you to write more, or to help you reorganize some parts of an essay that seem to lack connection or feel disjointed. Look for organizational patterns when you’re reading work by professional writers. Notice where they combine strategies (e.g., a problem-solution pattern that uses cause-and-effect organization, or a comparison-contrast pattern that uses narrative or chronology to develop similarities or differences). Pay attention to how different writers emphasize and develop their main ideas, and use what you find to inspire you in your own writing. Better yet, work on developing completely new patterns of your own.

Reference

  • This chapter was adapted from “Patterns of Organization and Methods of Development” in The Word on College Reading and Writing by Carol Burnell, Jaime Wood, Monique Babin, Susan Pesznecker, and Nicole Rosevear, which is licensed under a CC BY-NC 4.0 Licence. Adapted by Allison Kilgannon.

  • Peach and lavender pie” by Heather Joan is licensed under a CC BY-NC-ND 2.0 Licence.

  • “General to Specific vs. Specific to General Triangles” by Carol Burnell, Jaime Wood, Monique Babin, Susan Pesznecker, and Nicole Rosevear is under a CC BY-NC 4.0 Licence.

  • Kilgannon, Allison. “Patterns of Organization and Methods of Development.” Opentextbc.ca, 20 Aug. 2021, opentextbc.ca/advancedenglish/chapter/patterns-of-organization-and-methods-of-development/#:~:text=These%20four%20methods%20of%20development.

]]>
Patterns of Organization and Methods of Development

Patterns of organization can help your readers follow the ideas within your essay and your paragraphs, but they can also work as methods of development to help you recognize and further develop ideas and relationships in your writing. Here are some strategies that can help you with both organization and development in your essays.

Major Patterns of Organization

A fruit pie.

Read the following sentences:

  • Now take the pie out of the oven and let it cool on the stovetop.
  • Mix the dry ingredients with the liquid ingredients.
  • Set the pie crust aside while you make the filling.

How did it feel to read the above list? A bit confusing, I would guess. That’s because the steps for making a pie were not well organized, and the steps don’t include enough detail for us to know exactly what we should do. (Like what are the dry and liquid ingredients?) We all know that starting instructions from the beginning and giving each detailed step in the order it should happen is vital to having a good outcome, in this case a yummy pie! But it’s not always so simple to know how to organize or develop ideas, and sometimes there’s more than one way, which complicates things even further.

First, let’s take a look at a couple of ways to think about organization.

General to Specific or Specific to General

It might be useful to think about organizing your topic like a triangle:

Two triangles. The first is an inverted pyramid for General to Specific, the second is a pyramid for Specific to General.

The first triangle represents starting with the most general, big picture information first, moving then to more detailed and often more personal information later in the paper. The second triangle represents an organizational structure that starts with the specific, small scale information first and then moves to the more global, big picture stuff.

For example, if your topic is traffic in Vancouver, British Columbia, an essay that uses the general-to-specific organizational structure might begin this way:

Many people consider Vancouver, British Columbia, to be a relaxed place to live. They would be shocked to know how bad the traffic is traveling major arteries into the city and even driving around the city itself.

An essay that uses the specific-to-general structure might start like this:

Transit is crowded, parking is expensive, and vehicles stop and go through the main streets of the city of Vancouver, British Columbia, and that is just once travelers brave the crowded arteries to enter the city; Vancouver’s traffic problem does not lend itself to the relaxed atmosphere many believe the city to have.

What’s the difference between these two introductions? And how might they appeal to the intended audience for this essay in different ways? The first introduction is looking at the big picture of the problem and mentions pollution’s impact on all citizens in Portland, while the second introduction focuses on one specific family. The first helps readers see how vast the problem really is, and the second helps connect readers to a real family, making an emotional appeal from the very beginning. Neither introduction is necessarily better. You’ll choose one over the other based on the kind of tone you’d like to create and how you’d like to affect your audience. It’s completely up to you to make this decision.

Does the Triangle Mean the Essay Keeps Getting More Specific or More Broad until the Very End?

The triangle is kind of a general guide, meaning you’re allowed to move around within it all you want. For example, it’s possible that each of your paragraphs will be its own triangle, starting with the general or specific and moving out or in. However, if you begin very broadly, it might be effective to end your essay in a more specific, personal way. And if you begin with a personal story, consider ending your essay by touching on the global impact and importance of your topic.

Are There Other Ways to Think about Organizing My Ideas?

Yes! Rather than thinking about which of your ideas are most specific or personal or which are more broad or universal, you might consider one of the following ways of organizing your ideas:

  • Most important information first (consider what you want readers to focus on first)
  • Chronological order (the order in time that events take place)
  • Compare and contrast (ideas are organized together because of their relationship to each other)

The section on Methods of Development, below, offers more detail about some of these organizational patterns, along with some others.

Choose one of the following topics, and practice writing a few opening sentences like we did above, once using the general-to-specific format and once using the specific-to-general. Which do you like better? What audience would be attracted to which one? Share with peers to see how others tackled this challenge. How would you rewrite their sentences? Why? Discuss your changes and listen to how your peers have revised your sentences. Taking in other people’s ideas will help you see new ways to approach your own writing and thinking.
Topics:

  • Facing fears
  • Safety in sports
  • Community policing
  • Educating prisoners
  • Sex education

Methods of Development

The methods of development covered here are best used as ways to look at what’s already happening in your draft and to consider how you might emphasize or expand on any existing patterns. You might already be familiar with some of these patterns because teachers will sometimes assign them as the purpose for writing an essay. For example, you might have been asked to write a cause-and-effect essay or a comparison-and-contrast essay.

It’s important to emphasize here that patterns of organization or methods of developing content usually happen naturally as a consequence of the way the writer engages with and organizes information while writing. That is to say, most writers don’t sit down and say, “I think I’ll write a cause-and-effect essay today.” Instead, a writer might be more likely to be interested in a topic, say, the state of drinking water in the local community, and as the writer begins to explore the topic, certain cause-and-effect relationships between environmental pollutants and the community water supply may begin to emerge.

So if these patterns just occur naturally in writing, what’s the use in knowing about them? Well, sometimes you might be revising a draft and notice that some of your paragraphs are a bit underdeveloped. Maybe they lack a clear topic, or maybe they lack support. In either case, you can look to these common methods of development to find ways to sharpen those vague topics or to add support where needed. Do you have a clear cause statement somewhere but you haven’t explored the effects? Are you lacking detail somewhere where a narrative story or historical chronology can help build reader interest and add support? Are you struggling to define an idea that might benefit from some comparison or contrast? Read on to consider some of the ways that these strategies can help you in revision.

Cause and Effect (or Effect and Cause)

Do you see a potential cause-and-effect relationship developing in your draft? The cause-and-effect pattern may be used to identify one or more causes followed by one or more effects or results. Or you may reverse this sequence and describe effects first and then the cause or causes. For example, the causes of water pollution might be followed by its effects on both humans and animals. You may use obvious transitions to clarify cause and effect, such as “What are the results? Here are some of them…” or you might simply use the words cause, effect, and result, to cue the reader about your about the relationships that you’re establishing.

Problem-Solution

At some point does your essay explore a problem or suggest a solution? The problem-solution pattern is commonly used in identifying something that’s wrong and in contemplating what might be done to remedy the situation. There are probably more ways to organize a problem-solution approach, but but here are three possibilities:

  • Describe the problem, followed by the solution.
  • Propose the solution first and then describe the problems that motivated it.
  • Or a problem may be followed by several solutions, one of which is selected as the best.

When the solution is stated at the end of the paper, the pattern is sometimes called the delayed proposal. For a hostile audience, it may be effective to describe the problem, show why other solutions do not work, and finally suggest the favored solution. You can emphasize the words problem and solution to signal these sections of your paper for your reader.

Chronology or Narrative

Do you need to develop support for a topic where telling a story can illustrate some important concept for your readers? Material arranged chronologically is explained as it occurs in time. A chronological or narrative method of development might help you find a way to add both interest and content to your essay. Material arranged chronologically is explained as it occurs in time. This pattern may be used to establish what has happened. Chronology or narrative can be a great way to introduce your essay by providing a background or history behind your topic. Or you may want to tell a story to develop one or more points in the body of your essay. You can use transitional words like then, next, and finally to make the parts of the chronology clear.

Comparison and Contrast

Are you trying to define something? Do you need your readers to understand what something is and what it is not? The comparison-and-contrast method of development is particularly useful in extending a definition, or anywhere you need to show how a subject is like or unlike another subject. For example, the statement is often made that drug abuse is a medical problem instead of a criminal justice issue. An author might attempt to prove this point by comparing drug addiction to AIDS, cancer, or heart disease to redefine the term “addiction” as a medical problem. A statement in opposition to this idea could just as easily establish contrast by explaining all the ways that addiction is different from what we traditionally understand as an illness. In seeking to establish comparison or contrast in your writing, some words or terms that might be useful are by contrast, in comparison, while, some, and others.

Summary

These four methods of development—cause and effect, problem-solution, chronology or narrative, and comparison and contrast—are just a few ways to organize and develop ideas and content in your essays. It’s important to note that they should not be a starting point for writers who want to write something authentic—something that they care deeply about. Instead, they can be a great way to help you look for what’s already happening with your topic or in a draft, to help you to write more, or to help you reorganize some parts of an essay that seem to lack connection or feel disjointed. Look for organizational patterns when you’re reading work by professional writers. Notice where they combine strategies (e.g., a problem-solution pattern that uses cause-and-effect organization, or a comparison-contrast pattern that uses narrative or chronology to develop similarities or differences). Pay attention to how different writers emphasize and develop their main ideas, and use what you find to inspire you in your own writing. Better yet, work on developing completely new patterns of your own.

Reference

  • This chapter was adapted from “Patterns of Organization and Methods of Development” in The Word on College Reading and Writing by Carol Burnell, Jaime Wood, Monique Babin, Susan Pesznecker, and Nicole Rosevear, which is licensed under a CC BY-NC 4.0 Licence. Adapted by Allison Kilgannon.

  • Peach and lavender pie” by Heather Joan is licensed under a CC BY-NC-ND 2.0 Licence.

  • “General to Specific vs. Specific to General Triangles” by Carol Burnell, Jaime Wood, Monique Babin, Susan Pesznecker, and Nicole Rosevear is under a CC BY-NC 4.0 Licence.

  • Kilgannon, Allison. “Patterns of Organization and Methods of Development.” Opentextbc.ca, 20 Aug. 2021, opentextbc.ca/advancedenglish/chapter/patterns-of-organization-and-methods-of-development/#:~:text=These%20four%20methods%20of%20development.

]]>
<![CDATA[Welcome to Physics ]]> https://note.toshiki.dev/academic/physics/ https://note.toshiki.dev/academic/physics/ Thu, 01 Jul 2021 00:00:00 GMT Welcome to Physics ]]> Welcome to Physics ]]> <![CDATA[Formulas for IPhO 日本語版: Section 1 ]]> https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/1 https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/1 Thu, 01 Jul 2021 00:00:00 GMT Formulas for IPhO 日本語版: Section 1

1: 数学

1.1: Taylor 展開

  1. Taylor 展開(アバウトに切り捨てる:

    F(x)=F(x0)+F(n)(x0)(xx0)n/nF(x)=F\left(x_{0}\right)+\sum F^{(n)}\left(x_{0}\right)\left(x-x_{0}\right)^{n} / n

    線形近似(特別な場合):

    F(x)F(x0)+F(x0)(xx0)F(x) \approx F\left(x_{0}\right)+F^{\prime}\left(x_{0}\right)\left(x-x_{0}\right)

    x1|x| \ll 1 のときの例 ::

    sinxx,cosx1x2/2,ex1+x\sin x \approx x, \cos x \approx 1-x^{2} / 2, e^{x} \approx 1+x

    ln(1+x)x,(1+x)n1+nx\ln (1+x) \approx x,(1+x)^{n} \approx 1+n x

1.2: 摂動法

  1. 摂動法:摂動のない(直接解ける)問題の解を 00 番目の近似値として求め,前の似値に基づく次の近似値の補正を繰り返して解を求める.

1.3: 定数係数線形微分方程式

  1. 定数係数線形微分方程式 ay+by+cy=0a y^{\prime \prime}+b y^{\prime}+c y=0 の解:

    y=Aexp(λ1x)+Bexp(λ2x)y=A \exp \left(\lambda_1 x\right)+B \exp \left(\lambda_2 x\right) \text {. }

    ここで λ1,2\lambda_{1,2} は特性方程式 aλ2+bλ+c=0a \lambda^2+b \lambda+c=0 の異な る 2 解. もし a,b,ca, b, c が実数で特性方程式の解が複素数 λ1,2=γ±iω\lambda_{1,2}=\gamma \pm i \omega ならば,

    y=Ceγxsin(ωx+φ0)y=C e^{\gamma x} \sin \left(\omega x+\varphi_0\right)

1.4: 複素数

  1. 複素数

    z=a+bi=zeiφ,zˉ=abi=zeiφz2=zzˉ=a2+b2,φ=argz=arcsinbzRez=(z+zˉ)/2,Imz=(zzˉ)/2iz1z2=z1z2,argz1z2=argz1+argz2eiφ=cosφ+isinφcosφ=eiφ+eiφ2,sinφ=eiφeiφ2i\begin{gathered} z=a+b i=|z| e^{i \varphi}, \bar{z}=a-b i=|z| e^{-i \varphi} \\ |z|^2=z \bar{z}=a^2+b^2, \varphi=\arg z=\arcsin \frac{b}{|z|} \\ \operatorname{Re} z=(z+\bar{z}) / 2, \operatorname{Im} z=(z-\bar{z}) / 2 i \\ \left|z_1 z_2\right|=\left|z_1\right|\left|z_2\right|, \arg z_1 z_2=\arg z_1+\arg z_2 \\ e^{i \varphi}=\cos \varphi+i \sin \varphi \\ \cos \varphi=\frac{e^{i \varphi}+e^{-i \varphi}}{2}, \sin \varphi=\frac{e^{i \varphi}-e^{-i \varphi}}{2 i} \end{gathered}

1.5: ベクトルの内積と外積

  1. ベクトルの内積と外積は分配法則が成立する : a(b+c)=ab+aca(b+c)=a b+a c

    ab=ba=axbx+ayby+=abcosφa×b=absinφ,a×b=b×aa,ba×b=(aybzazby)ex+(azbxaxbz)ey+a×[b×c]=(ac)b(ab)c\begin{gathered} \boldsymbol{a} \cdot \boldsymbol{b}=\boldsymbol{b} \cdot \boldsymbol{a}=a_x b_x+a_y b_y+\cdots=a b \cos \varphi \\ |\boldsymbol{a} \times \boldsymbol{b}|=a b \sin \varphi, \boldsymbol{a} \times \boldsymbol{b}=-\boldsymbol{b} \times \boldsymbol{a} \perp \boldsymbol{a}, \boldsymbol{b} \\ \boldsymbol{a} \times \boldsymbol{b}=\left(a_y b_z-a_z b_y\right) \boldsymbol{e}_x+\left(a_z b_x-a_x b_z\right) \boldsymbol{e}_y+\cdots \\ \boldsymbol{a} \times[\boldsymbol{b} \times \boldsymbol{c}]=(\boldsymbol{a} \cdot \boldsymbol{c}) \boldsymbol{b}-(\boldsymbol{a} \cdot \boldsymbol{b}) \boldsymbol{c} \end{gathered}

    スカラー三重積(3 つのベクトルで張られる平行四面 体の体積):

    (a,b,c)a[b×c]=[a×b]c=(b,c,a)(\boldsymbol{a}, \boldsymbol{b}, \boldsymbol{c}) \equiv \boldsymbol{a} \cdot[\boldsymbol{b} \times \boldsymbol{c}]=[\boldsymbol{a} \times \boldsymbol{b}] \cdot \boldsymbol{c}=(\boldsymbol{b}, \boldsymbol{c}, \boldsymbol{a})

1.6: 余弦定理と正弦定理

  1. 余弦定理と正弦定理:

    c2=a2+b22abcosCa/sinA=b/sinB=2R\begin{aligned} & c^2=a^2+b^2-2 a b \cos C \\ & a / \sin A=b / \sin B=2 R \end{aligned}

1.7: 三角法

  1. sin(α±β)=sinαcosβ±cosαsinβcos(α±β)=cosαcosβsinαsinβtan(α±β)=(tanα±tanβ)/(1tanαtanβ)cos2α=1+cos2α2,sin2α=1cos2α2cosαcosβ=cos(α+β)+cos(αβ)2,cosα+cosβ=2(cosα+β2+cosαβ2),\begin{aligned} & \sin (\alpha \pm \beta)=\sin \alpha \cos \beta \pm \cos \alpha \sin \beta \\ & \cos (\alpha \pm \beta)=\cos \alpha \cos \beta \mp \sin \alpha \sin \beta \\ & \tan (\alpha \pm \beta)=(\tan \alpha \pm \tan \beta) /(1 \mp \tan \alpha \tan \beta) \\ & \cos ^2 \alpha=\frac{1+\cos 2 \alpha}{2}, \sin ^2 \alpha=\frac{1-\cos 2 \alpha}{2} \\ & \cos \alpha \cos \beta=\frac{\cos (\alpha+\beta)+\cos (\alpha-\beta)}{2}, \ldots \\ & \cos \alpha+\cos \beta=2\left(\cos \frac{\alpha+\beta}{2}+\cos \frac{\alpha-\beta}{2}\right), \ldots \end{aligned}

1.8: 円周角

  1. 円周角は中心角の半分. よって,直角三角形の斜辺は その外接円の直径. もし四角形の対角の和が 180 度な らば,それは円に内接する.

1.9: 三角形の面樍

  1. 三角形の面樍 =12aha=pr=p(pa)(pb)(pc)=abc/4R=\frac{1}{2} a h_a=p r=\sqrt{p(p-a)(p-b)(p-c)}=a b c / 4 R

1.10: 重心

  1. 三角形の重心は,中線の交点で,中線を 2:1 に内分する.\

1.11: ベクトルアプローチ

  1. 幾何の問題へのベクトルアプローチ.

1.12: 微分

  1. 微分:

    (fg)=fg+fg,f[g(x)]=f[g(x)]g(x)(sinx)=cosx,(cosx)=sinx(ex)=ex,(lnx)=1/x,(xn)=nxn1(arctanx)=1/(1+x2)(arcsinx)=(arccosx)=1/1x2\begin{gathered} (f g)^{\prime}=f^{\prime} g+f g^{\prime}, f[g(x)]^{\prime}=f^{\prime}[g(x)] g^{\prime}(x) \\ (\sin x)^{\prime}=\cos x,(\cos x)^{\prime}=-\sin x \\ \left(e^x\right)^{\prime}=e^x,(\ln x)^{\prime}=1 / x,\left(x^n\right)^{\prime}=n x^{n-1} \\ (\arctan x)^{\prime}=1 /\left(1+x^2\right) \\ (\arcsin x)^{\prime}=-(\arccos x)^{\prime}=1 / \sqrt{1-x^2} \end{gathered}

1.13: 積分

  1. 積分:微分の公式の左辺と右辺を入れ替えたものと同 じ(逆演算).例えば,

    xn dx=xn+1/(n+1).\int x^n \mathrm{~d} x=x^{n+1} /(n+1) .

    置換積分の特別な場合 :

    f(ax+b)dx=F(ax+b)/a.\int f(a x+b) \mathrm{d} x=F(a x+b) / a .

1.14: 円錐曲線

  1. 円錐曲線: a11x2+2a12xy+a22y2+a1x+a2y+a0=a_{11} x^2+2 a_{12} x y+a_{22} y^2+a_1 x+a_2 y+a_0= 0 で, a11=a22a_{11}=a_{22} ならば円, a11(a11a22a122)>0a_{11}\left(a_{11} a_{22}-a_{12}^2\right)>0 ならば楕円, <0\cdots<0 ならば双曲線, a11a22a122=0a_{11} a_{22}-a_{12}^2=0 ならば放物線. 楕円 : l1+l2=2a,α1=α2l_1+l_2=2 a, \alpha_1=\alpha_2 [訳 者注 : 焦点と曲線上の点を結ぶ直線と接線とのなす角 ], A=πabA=\pi a b. 双曲線 : l1l2=2a,α1+α2=0l_1-l_2=2 a, \alpha_1+\alpha_2=0. 放物線 :l+h=: l+h= const., α1=α2\alpha_1=\alpha_2.

1.15: 数值計算 & 台形規則

  1. 数值計算. f(x)=0f(x)=0 の解を求めるニュートン法 :

    xn+1=xnf(xn)/f(xn)x_{n+1}=x_n-f\left(x_n\right) / f^{\prime}\left(x_n\right)

    近似積分の台形規則:

    abf(x)dxba2n[f(x0)+2{f(x1)++f(xn1)}+f(xn)]\begin{array}{r} \int_a^b f(x) \mathrm{d} x \approx \frac{b-a}{2 n}\left[f\left(x_0\right)+2\left\{f\left(x_1\right)+\cdots\right.\right. \left.\left.+f\left(x_{n-1}\right)\right\}+f\left(x_n\right)\right] \end{array}

1.16: ベクトルの微分 & 積分

  1. ベクトルの微分と積分:成分ごとに微分/積分する.あるいは無限に近い22つのベクトルの差を求めることで 微分す.
]]>
Formulas for IPhO 日本語版: Section 1

1: 数学

1.1: Taylor 展開

  1. Taylor 展開(アバウトに切り捨てる:

    F(x)=F(x0)+F(n)(x0)(xx0)n/nF(x)=F\left(x_{0}\right)+\sum F^{(n)}\left(x_{0}\right)\left(x-x_{0}\right)^{n} / n

    線形近似(特別な場合):

    F(x)F(x0)+F(x0)(xx0)F(x) \approx F\left(x_{0}\right)+F^{\prime}\left(x_{0}\right)\left(x-x_{0}\right)

    x1|x| \ll 1 のときの例 ::

    sinxx,cosx1x2/2,ex1+x\sin x \approx x, \cos x \approx 1-x^{2} / 2, e^{x} \approx 1+x

    ln(1+x)x,(1+x)n1+nx\ln (1+x) \approx x,(1+x)^{n} \approx 1+n x

1.2: 摂動法

  1. 摂動法:摂動のない(直接解ける)問題の解を 00 番目の近似値として求め,前の似値に基づく次の近似値の補正を繰り返して解を求める.

1.3: 定数係数線形微分方程式

  1. 定数係数線形微分方程式 ay+by+cy=0a y^{\prime \prime}+b y^{\prime}+c y=0 の解:

    y=Aexp(λ1x)+Bexp(λ2x)y=A \exp \left(\lambda_1 x\right)+B \exp \left(\lambda_2 x\right) \text {. }

    ここで λ1,2\lambda_{1,2} は特性方程式 aλ2+bλ+c=0a \lambda^2+b \lambda+c=0 の異な る 2 解. もし a,b,ca, b, c が実数で特性方程式の解が複素数 λ1,2=γ±iω\lambda_{1,2}=\gamma \pm i \omega ならば,

    y=Ceγxsin(ωx+φ0)y=C e^{\gamma x} \sin \left(\omega x+\varphi_0\right)

1.4: 複素数

  1. 複素数

    z=a+bi=zeiφ,zˉ=abi=zeiφz2=zzˉ=a2+b2,φ=argz=arcsinbzRez=(z+zˉ)/2,Imz=(zzˉ)/2iz1z2=z1z2,argz1z2=argz1+argz2eiφ=cosφ+isinφcosφ=eiφ+eiφ2,sinφ=eiφeiφ2i\begin{gathered} z=a+b i=|z| e^{i \varphi}, \bar{z}=a-b i=|z| e^{-i \varphi} \\ |z|^2=z \bar{z}=a^2+b^2, \varphi=\arg z=\arcsin \frac{b}{|z|} \\ \operatorname{Re} z=(z+\bar{z}) / 2, \operatorname{Im} z=(z-\bar{z}) / 2 i \\ \left|z_1 z_2\right|=\left|z_1\right|\left|z_2\right|, \arg z_1 z_2=\arg z_1+\arg z_2 \\ e^{i \varphi}=\cos \varphi+i \sin \varphi \\ \cos \varphi=\frac{e^{i \varphi}+e^{-i \varphi}}{2}, \sin \varphi=\frac{e^{i \varphi}-e^{-i \varphi}}{2 i} \end{gathered}

1.5: ベクトルの内積と外積

  1. ベクトルの内積と外積は分配法則が成立する : a(b+c)=ab+aca(b+c)=a b+a c

    ab=ba=axbx+ayby+=abcosφa×b=absinφ,a×b=b×aa,ba×b=(aybzazby)ex+(azbxaxbz)ey+a×[b×c]=(ac)b(ab)c\begin{gathered} \boldsymbol{a} \cdot \boldsymbol{b}=\boldsymbol{b} \cdot \boldsymbol{a}=a_x b_x+a_y b_y+\cdots=a b \cos \varphi \\ |\boldsymbol{a} \times \boldsymbol{b}|=a b \sin \varphi, \boldsymbol{a} \times \boldsymbol{b}=-\boldsymbol{b} \times \boldsymbol{a} \perp \boldsymbol{a}, \boldsymbol{b} \\ \boldsymbol{a} \times \boldsymbol{b}=\left(a_y b_z-a_z b_y\right) \boldsymbol{e}_x+\left(a_z b_x-a_x b_z\right) \boldsymbol{e}_y+\cdots \\ \boldsymbol{a} \times[\boldsymbol{b} \times \boldsymbol{c}]=(\boldsymbol{a} \cdot \boldsymbol{c}) \boldsymbol{b}-(\boldsymbol{a} \cdot \boldsymbol{b}) \boldsymbol{c} \end{gathered}

    スカラー三重積(3 つのベクトルで張られる平行四面 体の体積):

    (a,b,c)a[b×c]=[a×b]c=(b,c,a)(\boldsymbol{a}, \boldsymbol{b}, \boldsymbol{c}) \equiv \boldsymbol{a} \cdot[\boldsymbol{b} \times \boldsymbol{c}]=[\boldsymbol{a} \times \boldsymbol{b}] \cdot \boldsymbol{c}=(\boldsymbol{b}, \boldsymbol{c}, \boldsymbol{a})

1.6: 余弦定理と正弦定理

  1. 余弦定理と正弦定理:

    c2=a2+b22abcosCa/sinA=b/sinB=2R\begin{aligned} & c^2=a^2+b^2-2 a b \cos C \\ & a / \sin A=b / \sin B=2 R \end{aligned}

1.7: 三角法

  1. sin(α±β)=sinαcosβ±cosαsinβcos(α±β)=cosαcosβsinαsinβtan(α±β)=(tanα±tanβ)/(1tanαtanβ)cos2α=1+cos2α2,sin2α=1cos2α2cosαcosβ=cos(α+β)+cos(αβ)2,cosα+cosβ=2(cosα+β2+cosαβ2),\begin{aligned} & \sin (\alpha \pm \beta)=\sin \alpha \cos \beta \pm \cos \alpha \sin \beta \\ & \cos (\alpha \pm \beta)=\cos \alpha \cos \beta \mp \sin \alpha \sin \beta \\ & \tan (\alpha \pm \beta)=(\tan \alpha \pm \tan \beta) /(1 \mp \tan \alpha \tan \beta) \\ & \cos ^2 \alpha=\frac{1+\cos 2 \alpha}{2}, \sin ^2 \alpha=\frac{1-\cos 2 \alpha}{2} \\ & \cos \alpha \cos \beta=\frac{\cos (\alpha+\beta)+\cos (\alpha-\beta)}{2}, \ldots \\ & \cos \alpha+\cos \beta=2\left(\cos \frac{\alpha+\beta}{2}+\cos \frac{\alpha-\beta}{2}\right), \ldots \end{aligned}

1.8: 円周角

  1. 円周角は中心角の半分. よって,直角三角形の斜辺は その外接円の直径. もし四角形の対角の和が 180 度な らば,それは円に内接する.

1.9: 三角形の面樍

  1. 三角形の面樍 =12aha=pr=p(pa)(pb)(pc)=abc/4R=\frac{1}{2} a h_a=p r=\sqrt{p(p-a)(p-b)(p-c)}=a b c / 4 R

1.10: 重心

  1. 三角形の重心は,中線の交点で,中線を 2:1 に内分する.\

1.11: ベクトルアプローチ

  1. 幾何の問題へのベクトルアプローチ.

1.12: 微分

  1. 微分:

    (fg)=fg+fg,f[g(x)]=f[g(x)]g(x)(sinx)=cosx,(cosx)=sinx(ex)=ex,(lnx)=1/x,(xn)=nxn1(arctanx)=1/(1+x2)(arcsinx)=(arccosx)=1/1x2\begin{gathered} (f g)^{\prime}=f^{\prime} g+f g^{\prime}, f[g(x)]^{\prime}=f^{\prime}[g(x)] g^{\prime}(x) \\ (\sin x)^{\prime}=\cos x,(\cos x)^{\prime}=-\sin x \\ \left(e^x\right)^{\prime}=e^x,(\ln x)^{\prime}=1 / x,\left(x^n\right)^{\prime}=n x^{n-1} \\ (\arctan x)^{\prime}=1 /\left(1+x^2\right) \\ (\arcsin x)^{\prime}=-(\arccos x)^{\prime}=1 / \sqrt{1-x^2} \end{gathered}

1.13: 積分

  1. 積分:微分の公式の左辺と右辺を入れ替えたものと同 じ(逆演算).例えば,

    xn dx=xn+1/(n+1).\int x^n \mathrm{~d} x=x^{n+1} /(n+1) .

    置換積分の特別な場合 :

    f(ax+b)dx=F(ax+b)/a.\int f(a x+b) \mathrm{d} x=F(a x+b) / a .

1.14: 円錐曲線

  1. 円錐曲線: a11x2+2a12xy+a22y2+a1x+a2y+a0=a_{11} x^2+2 a_{12} x y+a_{22} y^2+a_1 x+a_2 y+a_0= 0 で, a11=a22a_{11}=a_{22} ならば円, a11(a11a22a122)>0a_{11}\left(a_{11} a_{22}-a_{12}^2\right)>0 ならば楕円, <0\cdots<0 ならば双曲線, a11a22a122=0a_{11} a_{22}-a_{12}^2=0 ならば放物線. 楕円 : l1+l2=2a,α1=α2l_1+l_2=2 a, \alpha_1=\alpha_2 [訳 者注 : 焦点と曲線上の点を結ぶ直線と接線とのなす角 ], A=πabA=\pi a b. 双曲線 : l1l2=2a,α1+α2=0l_1-l_2=2 a, \alpha_1+\alpha_2=0. 放物線 :l+h=: l+h= const., α1=α2\alpha_1=\alpha_2.

1.15: 数值計算 & 台形規則

  1. 数值計算. f(x)=0f(x)=0 の解を求めるニュートン法 :

    xn+1=xnf(xn)/f(xn)x_{n+1}=x_n-f\left(x_n\right) / f^{\prime}\left(x_n\right)

    近似積分の台形規則:

    abf(x)dxba2n[f(x0)+2{f(x1)++f(xn1)}+f(xn)]\begin{array}{r} \int_a^b f(x) \mathrm{d} x \approx \frac{b-a}{2 n}\left[f\left(x_0\right)+2\left\{f\left(x_1\right)+\cdots\right.\right. \left.\left.+f\left(x_{n-1}\right)\right\}+f\left(x_n\right)\right] \end{array}

1.16: ベクトルの微分 & 積分

  1. ベクトルの微分と積分:成分ごとに微分/積分する.あるいは無限に近い22つのベクトルの差を求めることで 微分す.
]]>
<![CDATA[Formulas for IPhO 日本語版: Section 10 ]]> https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/10 https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/10 Thu, 01 Jul 2021 00:00:00 GMT Formulas for IPhO 日本語版: Section 10

10: 熱力学

10.1: pV=wMRTp V=\frac{w}{M} R T

  1. pV=wMRTp V=\frac{w}{M} R T.

10.2: モルの気体の内部エネルギー

  1. 1 モルの気体の内部エネルギー: U=i2RTU=\frac{i}{2} R T [訳者注: 単 原子分子理想気体 i=3i=3, 二原子分子理想気体 i=5]i=5].

10.3: 標準状態

  1. 標準状態での 1 モルの気体の体積は 22.4 L22.4 \mathrm{~L}.

10.4: 断熱過程

  1. 断熱過程: 音速に比べて遅く, 熱の出入りがない. pVγ=p V^\gamma= const. (TVγ1=\left(T V^{\gamma-1}=\right. const. )).

10.5: γ=Cp/Cv=(i+2)/i

  1. γ=cp/cv=(i+2)/i\gamma=c_p / c_v=(i+2) / i.

10.6: Boltzmann 分布

  1. Boltzmann 分布 :

    ρ=ρ0eMgh/RT=ρ0eU/kBT\rho=\rho_0 e^{-M g h / R T}=\rho_0 e^{-U / k_B T}

10.7: Maxwell 分布

  1. Maxwell 分布(v の速さをもつ分子の数)

    訳者注

    位相空間で v\boldsymbol{v}v+dv\boldsymbol{v}+\mathrm{d} \boldsymbol{v} の間にある分子の数の分布 であり,v の速さをもつ分子の数の分布とは異なる] emv2/2kBT\propto e^{-m \boldsymbol{v}^2 / 2 k_B T}

10.8: 大気圧

  1. 大気圧 : Δpp\Delta p \ll p ならば Δp=ρgΔh\Delta p=\rho g \Delta h.

10.9: 公式

  1. p=13mnv2=nkBT(np=\frac{1}{3} m n \overline{v^2}=n k_B T(n は数密度 ),v2=), \sqrt{\overline{\overline{v^2}}}= 3kBT/m,ν=vnS\sqrt{3 k_B T / m}, \nu=v n S.

10.10: Carnot サイクル

  1. Carnot サイクル : 断熱過程 2 つと等温過程 2 つ. STS-T 座標を用いることにより η=(T1T2)/T1\eta=\left(T_1-T_2\right) / T_1 を得る.

10.11: ヒートポンプ

  1. ヒートポンプ: Carnot サイクルの逆. η=T1T1T2\eta=\frac{T_1}{T_1-T_2}.

10.12: エントロピー

  1. エントロピー :dS=dQ/T: \mathrm{d} S=\mathrm{d} Q / T.

10.13: 熱力学第一法則

  1. 熱力学第一法則 : dU=dA+dQ\mathrm{d}^{\prime} U=\mathrm{d}^{\prime} A+\mathrm{d}^{\prime} Q

10.14: 熱力学第二法則

  1. 熱力学第二法則 : ΔS0\Delta S \geq 0 (また ηreal ηCarnot )\left.\eta_{\text {real }} \leq \eta_{\text {Carnot }}\right).

10.15: 気体のする仕事

  1. 気体のする仕事(ポイント 10 も参照):

    A=p dV, 断熱過程: A=i2Δ(pV)A=\int p \mathrm{~d} V, \quad \text { 断熱過程: } A=\frac{i}{2} \Delta(p V)

10.16: Dalton の法則

  1. Dalton の法則: p=p= pi\sum p_i

    訳者注

    理想気体のみ成立

10.17: 沸騰

  1. 沸騰: 飽和蒸気の圧力 pv=p0.2p_v=p_0 .2 液の界面では pv1+pv2=p0p_{v 1}+p_{v 2}=p_0.

10.18: 熱流

  1. 熱流: P=kSΔT/lP=k S \Delta T / l ( kk は熱伝導率). 直流回路に似て いる (PI,ΔTV,k1/ρ)(P \leftrightarrow I, \Delta T \leftrightarrow V, k \leftrightarrow 1 / \rho).

10.19: 熱容量

  1. 熱容量 : Q=c(T)dTQ=\int c(T) \mathrm{d} T. 固体では低温で cT3c \propto T^3, 高温で c=3NkBc=3 N k_B (Dulong-Petit の法則. ここで NN は結晶中の原子数)

10.20: 表面張力

  1. 表面張力 :

    U=Sσ,F=lσ,p=2σ/RU=S \sigma, F=l \sigma, p=2 \sigma / R

10.21: Stefan-Boltzmann の法則 (灰色体)

  1. Stefan-Boltzmann の法則 (灰色体) : P=εσAT4P=\varepsilon \sigma A T^4.

10.22: Wien の変位則

  1. Wien の変位則: νmax=AkBT/h(A\nu_{\max }=A k_B T / h(A \approx 2.8), λmax=hc/AkBT(A5)\lambda_{\max }=h c / A^{\prime} k_B T\left(A^{\prime} \approx 5\right).
]]>
Formulas for IPhO 日本語版: Section 10

10: 熱力学

10.1: pV=wMRTp V=\frac{w}{M} R T

  1. pV=wMRTp V=\frac{w}{M} R T.

10.2: モルの気体の内部エネルギー

  1. 1 モルの気体の内部エネルギー: U=i2RTU=\frac{i}{2} R T [訳者注: 単 原子分子理想気体 i=3i=3, 二原子分子理想気体 i=5]i=5].

10.3: 標準状態

  1. 標準状態での 1 モルの気体の体積は 22.4 L22.4 \mathrm{~L}.

10.4: 断熱過程

  1. 断熱過程: 音速に比べて遅く, 熱の出入りがない. pVγ=p V^\gamma= const. (TVγ1=\left(T V^{\gamma-1}=\right. const. )).

10.5: γ=Cp/Cv=(i+2)/i

  1. γ=cp/cv=(i+2)/i\gamma=c_p / c_v=(i+2) / i.

10.6: Boltzmann 分布

  1. Boltzmann 分布 :

    ρ=ρ0eMgh/RT=ρ0eU/kBT\rho=\rho_0 e^{-M g h / R T}=\rho_0 e^{-U / k_B T}

10.7: Maxwell 分布

  1. Maxwell 分布(v の速さをもつ分子の数)

    訳者注

    位相空間で v\boldsymbol{v}v+dv\boldsymbol{v}+\mathrm{d} \boldsymbol{v} の間にある分子の数の分布 であり,v の速さをもつ分子の数の分布とは異なる] emv2/2kBT\propto e^{-m \boldsymbol{v}^2 / 2 k_B T}

10.8: 大気圧

  1. 大気圧 : Δpp\Delta p \ll p ならば Δp=ρgΔh\Delta p=\rho g \Delta h.

10.9: 公式

  1. p=13mnv2=nkBT(np=\frac{1}{3} m n \overline{v^2}=n k_B T(n は数密度 ),v2=), \sqrt{\overline{\overline{v^2}}}= 3kBT/m,ν=vnS\sqrt{3 k_B T / m}, \nu=v n S.

10.10: Carnot サイクル

  1. Carnot サイクル : 断熱過程 2 つと等温過程 2 つ. STS-T 座標を用いることにより η=(T1T2)/T1\eta=\left(T_1-T_2\right) / T_1 を得る.

10.11: ヒートポンプ

  1. ヒートポンプ: Carnot サイクルの逆. η=T1T1T2\eta=\frac{T_1}{T_1-T_2}.

10.12: エントロピー

  1. エントロピー :dS=dQ/T: \mathrm{d} S=\mathrm{d} Q / T.

10.13: 熱力学第一法則

  1. 熱力学第一法則 : dU=dA+dQ\mathrm{d}^{\prime} U=\mathrm{d}^{\prime} A+\mathrm{d}^{\prime} Q

10.14: 熱力学第二法則

  1. 熱力学第二法則 : ΔS0\Delta S \geq 0 (また ηreal ηCarnot )\left.\eta_{\text {real }} \leq \eta_{\text {Carnot }}\right).

10.15: 気体のする仕事

  1. 気体のする仕事(ポイント 10 も参照):

    A=p dV, 断熱過程: A=i2Δ(pV)A=\int p \mathrm{~d} V, \quad \text { 断熱過程: } A=\frac{i}{2} \Delta(p V)

10.16: Dalton の法則

  1. Dalton の法則: p=p= pi\sum p_i

    訳者注

    理想気体のみ成立

10.17: 沸騰

  1. 沸騰: 飽和蒸気の圧力 pv=p0.2p_v=p_0 .2 液の界面では pv1+pv2=p0p_{v 1}+p_{v 2}=p_0.

10.18: 熱流

  1. 熱流: P=kSΔT/lP=k S \Delta T / l ( kk は熱伝導率). 直流回路に似て いる (PI,ΔTV,k1/ρ)(P \leftrightarrow I, \Delta T \leftrightarrow V, k \leftrightarrow 1 / \rho).

10.19: 熱容量

  1. 熱容量 : Q=c(T)dTQ=\int c(T) \mathrm{d} T. 固体では低温で cT3c \propto T^3, 高温で c=3NkBc=3 N k_B (Dulong-Petit の法則. ここで NN は結晶中の原子数)

10.20: 表面張力

  1. 表面張力 :

    U=Sσ,F=lσ,p=2σ/RU=S \sigma, F=l \sigma, p=2 \sigma / R

10.21: Stefan-Boltzmann の法則 (灰色体)

  1. Stefan-Boltzmann の法則 (灰色体) : P=εσAT4P=\varepsilon \sigma A T^4.

10.22: Wien の変位則

  1. Wien の変位則: νmax=AkBT/h(A\nu_{\max }=A k_B T / h(A \approx 2.8), λmax=hc/AkBT(A5)\lambda_{\max }=h c / A^{\prime} k_B T\left(A^{\prime} \approx 5\right).
]]>
<![CDATA[Formulas for IPhO 日本語版: Section 11 ]]> https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/11 https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/11 Thu, 01 Jul 2021 00:00:00 GMT Formulas for IPhO 日本語版: Section 11

11: 量子力学

11.1:p=hk

  1. p=k(p=h/λ),E=ω=hν\boldsymbol{p}=\hbar \boldsymbol{k}(|\boldsymbol{p}|=h / \lambda), E=\hbar \omega=h \nu.

11.2: 干渉

  1. 干渉 : 波動光学のように.

11.3: 不確定性

  1. 不確定性(数学の定理):

    ΔpΔx2,ΔEΔt2,ΔωΔt12\Delta p \Delta x \geq \frac{\hbar}{2}, \Delta E \Delta t \geq \frac{\hbar}{2}, \Delta \omega \Delta t \geq \frac{1}{2}

    滑らかでない場合の定性的な推定には hh の方が適する (ΔpΔxh(\Delta p \Delta x \approx h など )).

11.4: スペクトル

  1. スペクトル : hν=EnEmh \nu=E_n-E_m. スペクトル線の幅は寿 命に関係し, Γτ\Gamma \tau \approx \hbar.

11.5: 振動子

  1. 振動子(例えば分子)のエネルギー準位(固有振動数 ν0):En=(n+12)hν0\left.\nu_0\right): E_n=\left(n+\frac{1}{2}\right) h \nu_0. 多数の固有振動数の場合, E=hniνiE=\sum h n_i \nu_i.

11.6: トンネル効果

  1. トンネル効果: 幅 ll の障壁 Γ\Gamma は, Γτ(τ=\Gamma \tau \approx \hbar(\tau= l/Γ/m)l / \sqrt{\Gamma / m}) であれば容易に透過する.

11.7: Bohr モデル

  1. Bohr モデル : En1/n2E_n \propto-1 / n^2. (古典的に計算される) 円軌道では, 軌道の長さが波長 λ=h/mv\lambda=h / m v の整数倍.

11.8: Compton 効果

  1. Compton 効果: 光子が電子から散乱されると, 光子の Δλ=λC(1cosθ)\Delta \lambda=\lambda_C(1-\cos \theta)

11.9: 光電効果

  1. 光電効果: W+mvmax2/2=hνW+m v_{\max }^2 / 2=h \nu ( WW は仕事関数 )). IVI-V グラフ:光電流は阻止電圧 V=(hνW)/eV=-(h \nu-W) / e で始まり, 正方向に電圧が大きくなると緩和する.

11.10: Stefan-Boltzmann の法則

  1. Stefan-Boltzmann の法則 : P=σAT4P=\sigma A T^4
]]>
Formulas for IPhO 日本語版: Section 11

11: 量子力学

11.1:p=hk

  1. p=k(p=h/λ),E=ω=hν\boldsymbol{p}=\hbar \boldsymbol{k}(|\boldsymbol{p}|=h / \lambda), E=\hbar \omega=h \nu.

11.2: 干渉

  1. 干渉 : 波動光学のように.

11.3: 不確定性

  1. 不確定性(数学の定理):

    ΔpΔx2,ΔEΔt2,ΔωΔt12\Delta p \Delta x \geq \frac{\hbar}{2}, \Delta E \Delta t \geq \frac{\hbar}{2}, \Delta \omega \Delta t \geq \frac{1}{2}

    滑らかでない場合の定性的な推定には hh の方が適する (ΔpΔxh(\Delta p \Delta x \approx h など )).

11.4: スペクトル

  1. スペクトル : hν=EnEmh \nu=E_n-E_m. スペクトル線の幅は寿 命に関係し, Γτ\Gamma \tau \approx \hbar.

11.5: 振動子

  1. 振動子(例えば分子)のエネルギー準位(固有振動数 ν0):En=(n+12)hν0\left.\nu_0\right): E_n=\left(n+\frac{1}{2}\right) h \nu_0. 多数の固有振動数の場合, E=hniνiE=\sum h n_i \nu_i.

11.6: トンネル効果

  1. トンネル効果: 幅 ll の障壁 Γ\Gamma は, Γτ(τ=\Gamma \tau \approx \hbar(\tau= l/Γ/m)l / \sqrt{\Gamma / m}) であれば容易に透過する.

11.7: Bohr モデル

  1. Bohr モデル : En1/n2E_n \propto-1 / n^2. (古典的に計算される) 円軌道では, 軌道の長さが波長 λ=h/mv\lambda=h / m v の整数倍.

11.8: Compton 効果

  1. Compton 効果: 光子が電子から散乱されると, 光子の Δλ=λC(1cosθ)\Delta \lambda=\lambda_C(1-\cos \theta)

11.9: 光電効果

  1. 光電効果: W+mvmax2/2=hνW+m v_{\max }^2 / 2=h \nu ( WW は仕事関数 )). IVI-V グラフ:光電流は阻止電圧 V=(hνW)/eV=-(h \nu-W) / e で始まり, 正方向に電圧が大きくなると緩和する.

11.10: Stefan-Boltzmann の法則

  1. Stefan-Boltzmann の法則 : P=σAT4P=\sigma A T^4
]]>
<![CDATA[Formulas for IPhO 日本語版: Section 12 ]]> https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/12 https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/12 Thu, 01 Jul 2021 00:00:00 GMT Formulas for IPhO 日本語版: Section 12

12: Kepler の法則

12.1: F & U

  1. F=GMm/r2,U=GMm/rF=G M m / r^2, U=-G M m / r \text {. }

12.2: Kepler の第一法則

  1. Kepler の第一法則 (2 質点の重力相互作用):それぞ れの軌道は,系の質量中心に焦点を持つ楕円,双曲線, 放物線になる. これは Runge-Lenz ベクトルから得ら れる (ポイント 9).

12.3: Kepler の第二法則

  1. Kepler の第二法則(角運動量の保存): 中心力が働く 場にある質点について,その位置ベクトルは単位時間 に一定の面積を描く.

12.4: Kepler の第三法則

  1. Kepler の第三法則 :r2: r^{-2} に比例する力が働く場で楕円 軌道を描く複数の質点について, 周期は長半径の 32\frac{3}{2} 乗 に比例する :

    T12/T22=a13/a23T_1^2 / T_2^2=a_1^3 / a_2^3

12.5: 楕円軌道

  1. 重力場中で楕円軌道を描く質点の全エネルギー (K+U)(K+U) :

    E=GMm/2aE=-G M m / 2 a

12.6: 楕円率

  1. 楕円率が ε=d/a1\varepsilon=d / a \ll 1 の場合, 軌道は焦点をずらし た円形をしていると考えられる.

12.7: 楕円の性質

  1. 楕円の性質 :l1+l2=2al1: l_1+l_2=2 a ( l_1l2l_2 は焦点までの距 離). α1=α2\alpha_1=\alpha_2 (一方の焦点から出た光は他方の焦点に 反射する). S=πabS=\pi a b.

12.8: 円の中心

  1. 円とその円の中心に焦点をもつ楕円は長軸の部分での み接する.

12.9: nge-Lenz ベクトル

  1. Runge-Lenz ベクトル(楕円率ベクトル)[訳者注:こ のベクトルはむしろ離心率と関係する.そこでここで は離心率ベクトルとして知られるベクトルを代わりに 記す.これは焦点から近日点に向かう向きで,大きさ が離心率 ee に一致する.]:

    e=v×MGMmer= const. \boldsymbol{e}=\frac{\boldsymbol{v} \times \boldsymbol{M}}{G M m}-\boldsymbol{e}_r=\text { const. }

]]>
Formulas for IPhO 日本語版: Section 12

12: Kepler の法則

12.1: F & U

  1. F=GMm/r2,U=GMm/rF=G M m / r^2, U=-G M m / r \text {. }

12.2: Kepler の第一法則

  1. Kepler の第一法則 (2 質点の重力相互作用):それぞ れの軌道は,系の質量中心に焦点を持つ楕円,双曲線, 放物線になる. これは Runge-Lenz ベクトルから得ら れる (ポイント 9).

12.3: Kepler の第二法則

  1. Kepler の第二法則(角運動量の保存): 中心力が働く 場にある質点について,その位置ベクトルは単位時間 に一定の面積を描く.

12.4: Kepler の第三法則

  1. Kepler の第三法則 :r2: r^{-2} に比例する力が働く場で楕円 軌道を描く複数の質点について, 周期は長半径の 32\frac{3}{2} 乗 に比例する :

    T12/T22=a13/a23T_1^2 / T_2^2=a_1^3 / a_2^3

12.5: 楕円軌道

  1. 重力場中で楕円軌道を描く質点の全エネルギー (K+U)(K+U) :

    E=GMm/2aE=-G M m / 2 a

12.6: 楕円率

  1. 楕円率が ε=d/a1\varepsilon=d / a \ll 1 の場合, 軌道は焦点をずらし た円形をしていると考えられる.

12.7: 楕円の性質

  1. 楕円の性質 :l1+l2=2al1: l_1+l_2=2 a ( l_1l2l_2 は焦点までの距 離). α1=α2\alpha_1=\alpha_2 (一方の焦点から出た光は他方の焦点に 反射する). S=πabS=\pi a b.

12.8: 円の中心

  1. 円とその円の中心に焦点をもつ楕円は長軸の部分での み接する.

12.9: nge-Lenz ベクトル

  1. Runge-Lenz ベクトル(楕円率ベクトル)[訳者注:こ のベクトルはむしろ離心率と関係する.そこでここで は離心率ベクトルとして知られるベクトルを代わりに 記す.これは焦点から近日点に向かう向きで,大きさ が離心率 ee に一致する.]:

    e=v×MGMmer= const. \boldsymbol{e}=\frac{\boldsymbol{v} \times \boldsymbol{M}}{G M m}-\boldsymbol{e}_r=\text { const. }

]]>
<![CDATA[Formulas for IPhO 日本語版: Section 13 ]]> https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/13 https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/13 Thu, 01 Jul 2021 00:00:00 GMT Formulas for IPhO 日本語版: Section 13

13: 相対性理論

13.1:Lorentz 変換

  1. Lorentz 変換 (Minkowski 幾何学の 4 次元時空の回 転)(慣性系間の速度が V=Vex):β=V/c,γ=\left.\boldsymbol{V}=V \boldsymbol{e}_x\right): \beta=V / c, \gamma=

    1/1β2 として, ct=γ(ctβx),x=γ(xβct),y=yE/c=γ(E/cβpx),px=γ(pxβE/c),py=py ここで, E=mc21v2/c2=mc2+12mv2+px=mvx1v2/c2, etc. \begin{aligned} & 1 / \sqrt{1-\beta^2} \text { として, } \\ & \qquad c t^{\prime}=\gamma(c t-\beta x), x^{\prime}=\gamma(x-\beta c t), y^{\prime}=y \\ & E^{\prime} / c=\gamma\left(E / c-\beta p_x\right), p_x^{\prime}=\gamma\left(p_x-\beta E / c\right), p_y^{\prime}=p_y \\ & \text { ここで, } \\ & E=\frac{m c^2}{\sqrt{1-v^2 / c^2}}=m c^2+\frac{1}{2} m v^2+\cdots \\ & p_x=\frac{m v_x}{\sqrt{1-v^2 / c^2}}, \text { etc. } \end{aligned}

13.2: 4 元ベクトルの長

  1. 4 元ベクトルの長さ (スカラー量であり Lorentz 変換 で不変):

    s2=(ct)2x2y2z2(mc)2=(E/c)2px2py2pz2\begin{aligned} s^2 & =(c t)^2-x^2-y^2-z^2 \\ (m c)^2 & =(E / c)^2-p_x^2-p_y^2-p_z^2 \end{aligned}

13.3: 速度の加算

  1. 速度の加算 :

    vx=vx+V1+vxV/c2,vy=vyγ(1+vxV/c2)v_x=\frac{v_x^{\prime}+V}{1+v_x^{\prime} V / c^2}, v_y=\frac{v_y^{\prime}}{\gamma\left(1+v_x^{\prime} V / c^2\right)}

13.4: Doppler 効果

  1. Doppler 効果 :

    ν=γ(1+βcosθ)ν0\nu=\gamma(1+\beta \cos \theta) \nu_0

13.5: Minkowski 空間

  1. Minkowski 空間は, 時間が虚数( (tict)(t i c t) であれば Euclid 空間にすることができる. 回転角 φ\varphi に対して, tanφ=v/ic\tan \varphi=v / i c となり, sinφ,cosφ\sin \varphi, \cos \varphitanφ\tan \varphi で表して Euclid 幾何学の公式を適用する (Lorentz 変換).

13.6: 長さの縮み

  1. 長さの縮み : l=l0/γl^{\prime}=l_0 / \gamma.

13.7: 時間の遅れ

  1. 時間の遅れ: t=t0γt^{\prime}=t_0 \gamma.

13.8: 同時刻の相対性

  1. 同時刻の相対性 : Δt=γvΔx/c2\Delta t=-\gamma v \Delta x / c^2.

13.9: F=dp/dt

  1. F=dp/dt(=ddt(γmv))(\boldsymbol{F}=\mathrm{d} \boldsymbol{p} / \mathrm{d} t\left(=\frac{\mathrm{d}}{\mathrm{d} t}(\gamma m \boldsymbol{v})\right)( ここでの γ=\gamma= 1/1v2/c2)\left.1 / \sqrt{1-v^2 / c^2}\right)

13.10: 超相対論的極限

  1. 超相対論的極限 :vc,pmc,1(v/c)2: v \approx c, p \approx m c, \sqrt{1-(v / c)^2} \approx 2(1v/c)\sqrt{2(1-v / c)}

13.11: 電場と磁場の Lorentz 変換

  1. 電場と磁場の Lorentz 変換 : E=E,B=B\boldsymbol{E}_{\|}^{\prime}=\boldsymbol{E}_{\|}, \boldsymbol{B}_{\|}^{\prime}=\boldsymbol{B}_{\|},

    E/c=γ(E/c+v/c×B),B=γ(Bv/c×E/c)\begin{gathered} \boldsymbol{E}_{\perp}^{\prime} / c=\gamma\left(\boldsymbol{E}_{\perp} / c+\boldsymbol{v} / c \times \boldsymbol{B}_{\perp}\right), \\ \boldsymbol{B}_{\perp}^{\prime}=\gamma\left(\boldsymbol{B}_{\perp}-\boldsymbol{v} / c \times \boldsymbol{E}_{\perp} / c\right) \end{gathered}

]]>
Formulas for IPhO 日本語版: Section 13

13: 相対性理論

13.1:Lorentz 変換

  1. Lorentz 変換 (Minkowski 幾何学の 4 次元時空の回 転)(慣性系間の速度が V=Vex):β=V/c,γ=\left.\boldsymbol{V}=V \boldsymbol{e}_x\right): \beta=V / c, \gamma=

    1/1β2 として, ct=γ(ctβx),x=γ(xβct),y=yE/c=γ(E/cβpx),px=γ(pxβE/c),py=py ここで, E=mc21v2/c2=mc2+12mv2+px=mvx1v2/c2, etc. \begin{aligned} & 1 / \sqrt{1-\beta^2} \text { として, } \\ & \qquad c t^{\prime}=\gamma(c t-\beta x), x^{\prime}=\gamma(x-\beta c t), y^{\prime}=y \\ & E^{\prime} / c=\gamma\left(E / c-\beta p_x\right), p_x^{\prime}=\gamma\left(p_x-\beta E / c\right), p_y^{\prime}=p_y \\ & \text { ここで, } \\ & E=\frac{m c^2}{\sqrt{1-v^2 / c^2}}=m c^2+\frac{1}{2} m v^2+\cdots \\ & p_x=\frac{m v_x}{\sqrt{1-v^2 / c^2}}, \text { etc. } \end{aligned}

13.2: 4 元ベクトルの長

  1. 4 元ベクトルの長さ (スカラー量であり Lorentz 変換 で不変):

    s2=(ct)2x2y2z2(mc)2=(E/c)2px2py2pz2\begin{aligned} s^2 & =(c t)^2-x^2-y^2-z^2 \\ (m c)^2 & =(E / c)^2-p_x^2-p_y^2-p_z^2 \end{aligned}

13.3: 速度の加算

  1. 速度の加算 :

    vx=vx+V1+vxV/c2,vy=vyγ(1+vxV/c2)v_x=\frac{v_x^{\prime}+V}{1+v_x^{\prime} V / c^2}, v_y=\frac{v_y^{\prime}}{\gamma\left(1+v_x^{\prime} V / c^2\right)}

13.4: Doppler 効果

  1. Doppler 効果 :

    ν=γ(1+βcosθ)ν0\nu=\gamma(1+\beta \cos \theta) \nu_0

13.5: Minkowski 空間

  1. Minkowski 空間は, 時間が虚数( (tict)(t i c t) であれば Euclid 空間にすることができる. 回転角 φ\varphi に対して, tanφ=v/ic\tan \varphi=v / i c となり, sinφ,cosφ\sin \varphi, \cos \varphitanφ\tan \varphi で表して Euclid 幾何学の公式を適用する (Lorentz 変換).

13.6: 長さの縮み

  1. 長さの縮み : l=l0/γl^{\prime}=l_0 / \gamma.

13.7: 時間の遅れ

  1. 時間の遅れ: t=t0γt^{\prime}=t_0 \gamma.

13.8: 同時刻の相対性

  1. 同時刻の相対性 : Δt=γvΔx/c2\Delta t=-\gamma v \Delta x / c^2.

13.9: F=dp/dt

  1. F=dp/dt(=ddt(γmv))(\boldsymbol{F}=\mathrm{d} \boldsymbol{p} / \mathrm{d} t\left(=\frac{\mathrm{d}}{\mathrm{d} t}(\gamma m \boldsymbol{v})\right)( ここでの γ=\gamma= 1/1v2/c2)\left.1 / \sqrt{1-v^2 / c^2}\right)

13.10: 超相対論的極限

  1. 超相対論的極限 :vc,pmc,1(v/c)2: v \approx c, p \approx m c, \sqrt{1-(v / c)^2} \approx 2(1v/c)\sqrt{2(1-v / c)}

13.11: 電場と磁場の Lorentz 変換

  1. 電場と磁場の Lorentz 変換 : E=E,B=B\boldsymbol{E}_{\|}^{\prime}=\boldsymbol{E}_{\|}, \boldsymbol{B}_{\|}^{\prime}=\boldsymbol{B}_{\|},

    E/c=γ(E/c+v/c×B),B=γ(Bv/c×E/c)\begin{gathered} \boldsymbol{E}_{\perp}^{\prime} / c=\gamma\left(\boldsymbol{E}_{\perp} / c+\boldsymbol{v} / c \times \boldsymbol{B}_{\perp}\right), \\ \boldsymbol{B}_{\perp}^{\prime}=\gamma\left(\boldsymbol{B}_{\perp}-\boldsymbol{v} / c \times \boldsymbol{E}_{\perp} / c\right) \end{gathered}

]]>
<![CDATA[Formulas for IPhO 日本語版: Section 2 ]]> https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/2 https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/2 Thu, 01 Jul 2021 00:00:00 GMT Formulas for IPhO 日本語版: Section 2

2: 一般的な推奨事

  1. 全ての計算式の正しさを確かめる:a) 次元を調べる. b) 簡単で特別な場合を調べる(2 つの変数が等しい, 1 つの変数が 0 または \infty ). c) 解の定性的な挙動の妥当 性を調ベる. 2.もし問題文中に驚くベき偶然の一致があれば(例えば 2 つのものが同じ), 解答の鍵はそこにあるかもしれ ない.
  2. 問題文中の推奨事項をよく読む. 些細な部分に重要な 情報が含まれている場合があるので,問題文の文言に 注意する. かなり時間をかけても問題が解けない場合 は, 問題を誤解しているかもしれないので, もう一度 問題文を読む.
  3. 長くて時間のかかる計算は, 簡略化しなければならな い始めの方程式を全て書き出したのち, 最後(他の全 てが終わったとき) まで先送りする.
  4. 絶望的に難しいと思われる問題でも,たいてい非常に シンプルな解法がある.オリンピックの問題に限って 言えば,絶対に解ける.
  5. 実験では, a) 測定するほどの時問が無いとしても, 実 験計画の概略を書く,b) 結果の正確さを高める方法を 考える,c) 測定した值を全て(表として)書き出す.
]]>
Formulas for IPhO 日本語版: Section 2

2: 一般的な推奨事

  1. 全ての計算式の正しさを確かめる:a) 次元を調べる. b) 簡単で特別な場合を調べる(2 つの変数が等しい, 1 つの変数が 0 または \infty ). c) 解の定性的な挙動の妥当 性を調ベる. 2.もし問題文中に驚くベき偶然の一致があれば(例えば 2 つのものが同じ), 解答の鍵はそこにあるかもしれ ない.
  2. 問題文中の推奨事項をよく読む. 些細な部分に重要な 情報が含まれている場合があるので,問題文の文言に 注意する. かなり時間をかけても問題が解けない場合 は, 問題を誤解しているかもしれないので, もう一度 問題文を読む.
  3. 長くて時間のかかる計算は, 簡略化しなければならな い始めの方程式を全て書き出したのち, 最後(他の全 てが終わったとき) まで先送りする.
  4. 絶望的に難しいと思われる問題でも,たいてい非常に シンプルな解法がある.オリンピックの問題に限って 言えば,絶対に解ける.
  5. 実験では, a) 測定するほどの時問が無いとしても, 実 験計画の概略を書く,b) 結果の正確さを高める方法を 考える,c) 測定した值を全て(表として)書き出す.
]]>
<![CDATA[Formulas for IPhO 日本語版: Section 3 ]]> https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/3 https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/3 Thu, 01 Jul 2021 00:00:00 GMT Formulas for IPhO 日本語版: Section 3

3: 運動学

3.1: 質点

  1. 質点または剛体の並進運動の場合(積分 → グラフの下 の面積):

    v=dxdt,x=vdt(x=vx dt など )a=dvdt=d2xdt2,v=adtt=vx1 dx=ax1 dvx,x=vxax dvx\begin{gathered} \boldsymbol{v}=\frac{\mathrm{d} \boldsymbol{x}}{\mathrm{d} t}, \boldsymbol{x}=\int \boldsymbol{v} \mathrm{d} t\left(x=\int v_x \mathrm{~d} t \text { など }\right) \\ \boldsymbol{a}=\frac{\mathrm{d} \boldsymbol{v}}{\mathrm{d} t}=\frac{\mathrm{d}^2 \boldsymbol{x}}{\mathrm{d} t^2}, \boldsymbol{v}=\int \boldsymbol{a} \mathrm{d} t \\ t=\int v_x^{-1} \mathrm{~d} x=\int a_x^{-1} \mathrm{~d} v_x, x=\int \frac{v_x}{a_x} \mathrm{~d} v_x \end{gathered}

    もし aa が定数ならば, これらの積分は簡単に求めるこ とができて, 例えば

    x=v0t+at2/2=(v2v02)/2ax=v_0 t+a t^2 / 2=\left(v^2-v_0^2\right) / 2 a \text {. }

3.2: 回転運動

  1. 回転運動は, 並進運動と似ていて:

    ω=dφ/dt,ε=dω/dta=τdv/dt+nv2/R\begin{aligned} \omega & =\mathrm{d} \varphi / \mathrm{d} t, \varepsilon=\mathrm{d} \omega / \mathrm{d} t \\ \boldsymbol{a} & =\boldsymbol{\tau} \mathrm{d} v / \mathrm{d} t+\boldsymbol{n} v^2 / R \end{aligned}

3.3: 曲線運動

  1. 曲線運動は,ポイント 1 と同じだが,ベクトルは線速 度,加速度,経路長に置き換える.

3.4: 剛体の運動

  1. 剛体の運動:
    • vAcosα=vBcosβv_A \cos \alpha=v_B \cos \beta ここで, vA\boldsymbol{v}_AvB\boldsymbol{v}_B は剛体上の点 AABB の速度, α\alphaβ\betavA\boldsymbol{v}_AvB\boldsymbol{v}_B が直線 ABA B となす角.
    • 瞬間回転中心 (#質点の軌道 の曲率中心)は, a\boldsymbol{a}b\boldsymbol{b} に下ろした垂線の交点. 又は もし vA,vBAB\boldsymbol{v}_A, \boldsymbol{v}_B \perp A B ならば, vA\boldsymbol{v}_AvB\boldsymbol{v}_B の先端を結ぶ 直線と ABA B の交点.

3.5: 非慣性系

  1. 非慣性系:

    v2=v0+v1,a2=a0+a1+ω2R+aCor ここで, aCorv1. もし v1=0 なら aCor=0.\begin{array}{r} \quad \boldsymbol{v}_2=\boldsymbol{v}_0+\boldsymbol{v}_1, \boldsymbol{a}_2=\boldsymbol{a}_0+\boldsymbol{a}_1+\omega^2 \boldsymbol{R}+\boldsymbol{a}_{C o r} \\ \text { ここで, } \boldsymbol{a}_{C o r} \perp \boldsymbol{v}_1 . \text { もし } \boldsymbol{v}_1=0 \text { なら } \boldsymbol{a}_{C o r}=0 . \end{array}

3.6: 弾道問題

  1. 弾道問題:到達可能な範囲は

    yv02/(2g)gx2/(2v02)y \leq v_0^2 /(2 g)-g x^2 /\left(2 v_0^2\right)

    最適な弾道では, 初速度と終速(衝突時の速度)が垂直 になる.

3.7: 最短経路

  1. 最短経路を求めるには,Fermat と Huygens の原理が 使える.

3.8: ベクトル

  1. ベクトル(速度,加速度)を求めるには,その向きと (場合によっては傾いた)ある軸への射影を求めれば 充分.
]]>
Formulas for IPhO 日本語版: Section 3

3: 運動学

3.1: 質点

  1. 質点または剛体の並進運動の場合(積分 → グラフの下 の面積):

    v=dxdt,x=vdt(x=vx dt など )a=dvdt=d2xdt2,v=adtt=vx1 dx=ax1 dvx,x=vxax dvx\begin{gathered} \boldsymbol{v}=\frac{\mathrm{d} \boldsymbol{x}}{\mathrm{d} t}, \boldsymbol{x}=\int \boldsymbol{v} \mathrm{d} t\left(x=\int v_x \mathrm{~d} t \text { など }\right) \\ \boldsymbol{a}=\frac{\mathrm{d} \boldsymbol{v}}{\mathrm{d} t}=\frac{\mathrm{d}^2 \boldsymbol{x}}{\mathrm{d} t^2}, \boldsymbol{v}=\int \boldsymbol{a} \mathrm{d} t \\ t=\int v_x^{-1} \mathrm{~d} x=\int a_x^{-1} \mathrm{~d} v_x, x=\int \frac{v_x}{a_x} \mathrm{~d} v_x \end{gathered}

    もし aa が定数ならば, これらの積分は簡単に求めるこ とができて, 例えば

    x=v0t+at2/2=(v2v02)/2ax=v_0 t+a t^2 / 2=\left(v^2-v_0^2\right) / 2 a \text {. }

3.2: 回転運動

  1. 回転運動は, 並進運動と似ていて:

    ω=dφ/dt,ε=dω/dta=τdv/dt+nv2/R\begin{aligned} \omega & =\mathrm{d} \varphi / \mathrm{d} t, \varepsilon=\mathrm{d} \omega / \mathrm{d} t \\ \boldsymbol{a} & =\boldsymbol{\tau} \mathrm{d} v / \mathrm{d} t+\boldsymbol{n} v^2 / R \end{aligned}

3.3: 曲線運動

  1. 曲線運動は,ポイント 1 と同じだが,ベクトルは線速 度,加速度,経路長に置き換える.

3.4: 剛体の運動

  1. 剛体の運動:
    • vAcosα=vBcosβv_A \cos \alpha=v_B \cos \beta ここで, vA\boldsymbol{v}_AvB\boldsymbol{v}_B は剛体上の点 AABB の速度, α\alphaβ\betavA\boldsymbol{v}_AvB\boldsymbol{v}_B が直線 ABA B となす角.
    • 瞬間回転中心 (#質点の軌道 の曲率中心)は, a\boldsymbol{a}b\boldsymbol{b} に下ろした垂線の交点. 又は もし vA,vBAB\boldsymbol{v}_A, \boldsymbol{v}_B \perp A B ならば, vA\boldsymbol{v}_AvB\boldsymbol{v}_B の先端を結ぶ 直線と ABA B の交点.

3.5: 非慣性系

  1. 非慣性系:

    v2=v0+v1,a2=a0+a1+ω2R+aCor ここで, aCorv1. もし v1=0 なら aCor=0.\begin{array}{r} \quad \boldsymbol{v}_2=\boldsymbol{v}_0+\boldsymbol{v}_1, \boldsymbol{a}_2=\boldsymbol{a}_0+\boldsymbol{a}_1+\omega^2 \boldsymbol{R}+\boldsymbol{a}_{C o r} \\ \text { ここで, } \boldsymbol{a}_{C o r} \perp \boldsymbol{v}_1 . \text { もし } \boldsymbol{v}_1=0 \text { なら } \boldsymbol{a}_{C o r}=0 . \end{array}

3.6: 弾道問題

  1. 弾道問題:到達可能な範囲は

    yv02/(2g)gx2/(2v02)y \leq v_0^2 /(2 g)-g x^2 /\left(2 v_0^2\right)

    最適な弾道では, 初速度と終速(衝突時の速度)が垂直 になる.

3.7: 最短経路

  1. 最短経路を求めるには,Fermat と Huygens の原理が 使える.

3.8: ベクトル

  1. ベクトル(速度,加速度)を求めるには,その向きと (場合によっては傾いた)ある軸への射影を求めれば 充分.
]]>
<![CDATA[Formulas for IPhO 日本語版: Section 4 ]]> https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/4 https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/4 Thu, 01 Jul 2021 00:00:00 GMT Formulas for IPhO 日本語版: Section 4

4: 力学

4.1: 剛体の二次元的な平衡

  1. 剛体の二次元的な平衡 : 力についての 2 つの式とトル クについての 1 つの式. 1 (又は 2 )個の力についての 式は 1(又は 2)個のトルクについての式で代用でき る. トルクの方が良い場合が多く,原点を適切に選択 することで「退屈な」力を消すことができる. もし 2 点 のみに力がかかっているならば,(正味の)力がかかっ ている直線は一致する. 3 点であれば, 3 つの直線は 1 点で交わる.

4.2: 垂直抗力

  1. 垂直抗力と摩擦力は 1 つの力に合成でき, 垂直抗力に 対して arctanμ\arctan \mu の角度で接触点に加わる.

4.3: 並進運動と回転運動

  1. 並進運動と回転運動についての Newton の第二法則:

    F=ma,M=Iε(M=r×F)\boldsymbol{F}=m \boldsymbol{a}, \boldsymbol{M}=I \boldsymbol{\varepsilon} \quad(\boldsymbol{M}=\boldsymbol{r} \times \boldsymbol{F})

    二次元の場合には MMε\varepsilon は本質的にスカラーで, M=Fl=Ftr(lM=F l=F_t r(l は力のうでの長さ ))

4.4: 一般化座標

  1. 一般化座標. 系の状態が 1 つの変数 ξ\xi とその時間微分 ξ˙\dot{\xi} で表され,ポテンシャルエネルギーが U=U(ξ)U=U(\xi), 運動エネルギーが K=μξ2/2K=\mu \xi^2 / 2 であるならば, μξ¨=\mu \ddot{\xi}= dU(ξ)/dξ-\mathrm{d} U(\xi) / \mathrm{d} \xi. (したがって並進運動では, 力はポテン シャルエネルギーの微分)

4.5: 系質点

  1. 系が質点 mim_i で構成されているとき:

    rc=miri/mj,P=miviL=miri×vi,K=mivi2/2Iz=mi(xi2+yi2)=(x2+y2)dm\begin{aligned} & \boldsymbol{r}_c=\sum m_i \boldsymbol{r}_i / \sum m_j, \boldsymbol{P}=\sum m_i \boldsymbol{v}_i \\ & \boldsymbol{L}=\sum m_i \boldsymbol{r}_i \times \boldsymbol{v}_i, K=\sum m_i v_i^2 / 2 \\ & I_z=\sum m_i\left(x_i^2+y_i^2\right)=\int\left(x^2+y^2\right) \mathrm{d} m \\ & \end{aligned}

4.6: 質量中心の速度

  1. 質量中心の速度が vc\boldsymbol{v}_c であるような系 (添え字 cc は質量 中心についての物理量であることを示す):

    L=Lc+MΣRc×vc,K=Kc+MΣvc2/2P=Pc+MΣvc.\begin{gathered} \boldsymbol{L}=\boldsymbol{L}_c+M_{\Sigma} \boldsymbol{R}_c \times \boldsymbol{v}_c, K=K_c+M_{\Sigma} v_c^2 / 2 \\ \boldsymbol{P}=\boldsymbol{P}_c+M_{\Sigma} \boldsymbol{v}_c . \end{gathered}

4.7: Steiner 定理

  1. Steiner の定理(平行軸の定理)も同じような形で は質量中心の回転軸からの距離):

    I=Ic+mb2I=I_c+m b^2

4.8: ポイント 6

  1. ポイント 6 の P\boldsymbol{P}L\boldsymbol{L} を用いて, Newton の第二法則 :

    FΣ=dP/dt,MΣ=dL/dt\boldsymbol{F}_{\Sigma}=\mathrm{d} \boldsymbol{P} / \mathrm{d} t, \boldsymbol{M}_{\Sigma}=\mathrm{d} \boldsymbol{L} / \mathrm{d} t

4.9: ポイント 5

  1. ポイント 5 にに加えて,質量中心を通る zz 軸に対する慣性モ一メントは Iz0=I_{z 0}= i,jmimj[(xixj)2+(yiyj)2]/(2MΣ)\sum_{i, j} m_i m_j\left[\left(x_i-x_j\right)^2+\left(y_i-y_j\right)^2\right] /\left(2 M_{\Sigma}\right)

4.10: 原点に対する慣性

  1. 原点に対する慣性モ一メント θ=miri2\theta=\sum m_i r_i^2 は, 2θ=Ix+Iy+Iz2 \theta=I_x+I_y+I_z を用いることで二次元物体や等 方性のある物体の IzI_z を計算するのに有用.

4.11: 相当単振子の長

  1. 相当単振子の長さが l~\tilde{l} である物理振子 :

    ω2(l)=g/(l+Ic/ml)ω(l)=ω(l~l)=g/l~,l~=l+Ic/ml\begin{aligned} & \omega^2(l)=g /\left(l+I_c / m l\right) \\ & \omega(l)=\omega(\tilde{l}-l)=\sqrt{g / \tilde{l}}, \quad \tilde{l}=l+I_c / m l \\ & \end{aligned}

4.12: 慣性モーメントの係数

  1. 慣性モーメントの係数 : 円柱 12\frac{1}{2}, 球 25\frac{2}{5}, 球殼 23\frac{2}{3}, 棒 112\frac{1}{12} (端に対しては 13\frac{1}{3} ), 正方形 16\frac{1}{6}.

4.13: よく使われる保存則

  1. よく使われる保存則:エネルギー(弾性衝突,摩擦な し), 運動量(正味の外力なし, 各方向について成立), 角運動量(正味の外トルクなし, 例えば, 外力のうでの 長さが 0 (これが 2 又は 3 点のまわりに成り立てば運 動量保存で代用できる))

4.14: 非慣性系における見かけの力

  1. 非慣性系における見かけの力 : 慣性力 ma-m a, 遠心力 mω2Rm \omega^2 \boldsymbol{R}, Coriolis 力 2mv×Ω2 m \boldsymbol{v} \times \Omega (避けた方がよい. 速 度に垂直なので仕事はしない).

4.15: 傾いた座標

  1. 傾いた座標:斜面上での運動については, 斜面に平行 と垂直な方向に軸をとるのがよい。このとき重力加速 度は xx 成分と yy 成分をもつ. 軸は斜交することもある が, v=vxex+vyey\boldsymbol{v}=v_x \boldsymbol{e}_x+v_y \boldsymbol{e}_y のとき vxv_xv\boldsymbol{v}xx 軸への射 影ではない.

4.16: 2 つの物体の衝突

  1. 2 つの物体の衝突 : 保存されるのは, a) 全運動量, b) 全角運動量,c) 一方の物体の衝突点に関する角運動量, d) 全エネルギー(弾性衝突の場合, 摩擦がある場合 は, 摩擦力に垂直な方向の運動エネルギーが保存される. e) 衝突中に滑りが止まったならば,接触点の最終 速度は接触面上にある. f) 滑りが止まらなかったなら ば, 一方の物体から他方に伝わる運動量は, 接触面の 法線と arctanμ\arctan \mu の角度をなす.

4.17: 剛体のすべての運動

  1. 剛体のすべての運動は (物体の各点の速度を見ると) 瞬 間回転中心 CC まわりの回転として表せる. 物体上の点 PPCC からの距離は PP の軌跡の曲率半径とは異なる ことに注意せよ.

4.18: 紐の張力

  1. 紐の張力:重さのある吊り紐では, 張力の水平成分は 一定で垂直成分は下にある紐の重さにより変わる. 滑 らかな面の上の紐による(単位長さあたりの)力は,そ の曲率半径と張力で決まり, N=T/RN=T / R. 似た場合と して, 表面張力による圧力は p=2σ/Rp=2 \sigma / R. 導出には直 径に沿った圧力を調ベる.

4.19: 液体の表面

  1. 液体の表面は(表面張力を無視すれば)等ポテンシャ ル面になる. 非圧縮性流体では, ww をポテンシャルエ ネルギーの体積密度として, p=P0wp=P_0-w.

4.20: 非圧縮性流体に対する Bernoulli の法則

  1. 非圧縮性流体に対する Bernoulli の法則:

    p+12ρv2+ρϕ= const. p+\frac{1}{2} \rho v^2+\rho \phi=\text { const. }

    一様な重力場では ϕ=gh\phi=g h. 比熱が cp[ J/kg]c_p[\mathrm{~J} / \mathrm{kg}] である気 体では,

    12v2+cpT= const. \frac{1}{2} v^2+c_p T=\text { const. }

4.21: 直線的な流線

  1. 直線的な流線に沾う運動量の連続性 : p+ρv2=p+\rho v^2= const.

4.22: 断熱不変量

  1. 断熱不変量 : 振動する系の 1 周期の間のパラメータの 相対的な変化が小さければ,位相空間( xpx-p 座標で表さ れる)上に書かれるループの面積は非常に高い精度で 保存される.

4.23: 安定性

  1. 安定性を調ベるには, a) ポテンシャルエネルギー最小 の原理,又は b) 仮想仕事の原理を用いる.

4.24: 空間的に有限な運動に対する Virial 定理

  1. 空間的に有限な運動に対する Virial 定理:a) もし FrF \propto|\boldsymbol{r}| ならば K=U\langle K\rangle=\langle U\rangle (時間平均). b) もし Fr2F \propto|\boldsymbol{r}|^{-2} ならば 2K=U2\langle K\rangle=-\langle U\rangle.

4.25: Tsiolkovsky 公式

  1. Tsiolkovsky の公式(ロケット): Δv=ulnMm\Delta v=u \ln \frac{M}{m}
]]>
Formulas for IPhO 日本語版: Section 4

4: 力学

4.1: 剛体の二次元的な平衡

  1. 剛体の二次元的な平衡 : 力についての 2 つの式とトル クについての 1 つの式. 1 (又は 2 )個の力についての 式は 1(又は 2)個のトルクについての式で代用でき る. トルクの方が良い場合が多く,原点を適切に選択 することで「退屈な」力を消すことができる. もし 2 点 のみに力がかかっているならば,(正味の)力がかかっ ている直線は一致する. 3 点であれば, 3 つの直線は 1 点で交わる.

4.2: 垂直抗力

  1. 垂直抗力と摩擦力は 1 つの力に合成でき, 垂直抗力に 対して arctanμ\arctan \mu の角度で接触点に加わる.

4.3: 並進運動と回転運動

  1. 並進運動と回転運動についての Newton の第二法則:

    F=ma,M=Iε(M=r×F)\boldsymbol{F}=m \boldsymbol{a}, \boldsymbol{M}=I \boldsymbol{\varepsilon} \quad(\boldsymbol{M}=\boldsymbol{r} \times \boldsymbol{F})

    二次元の場合には MMε\varepsilon は本質的にスカラーで, M=Fl=Ftr(lM=F l=F_t r(l は力のうでの長さ ))

4.4: 一般化座標

  1. 一般化座標. 系の状態が 1 つの変数 ξ\xi とその時間微分 ξ˙\dot{\xi} で表され,ポテンシャルエネルギーが U=U(ξ)U=U(\xi), 運動エネルギーが K=μξ2/2K=\mu \xi^2 / 2 であるならば, μξ¨=\mu \ddot{\xi}= dU(ξ)/dξ-\mathrm{d} U(\xi) / \mathrm{d} \xi. (したがって並進運動では, 力はポテン シャルエネルギーの微分)

4.5: 系質点

  1. 系が質点 mim_i で構成されているとき:

    rc=miri/mj,P=miviL=miri×vi,K=mivi2/2Iz=mi(xi2+yi2)=(x2+y2)dm\begin{aligned} & \boldsymbol{r}_c=\sum m_i \boldsymbol{r}_i / \sum m_j, \boldsymbol{P}=\sum m_i \boldsymbol{v}_i \\ & \boldsymbol{L}=\sum m_i \boldsymbol{r}_i \times \boldsymbol{v}_i, K=\sum m_i v_i^2 / 2 \\ & I_z=\sum m_i\left(x_i^2+y_i^2\right)=\int\left(x^2+y^2\right) \mathrm{d} m \\ & \end{aligned}

4.6: 質量中心の速度

  1. 質量中心の速度が vc\boldsymbol{v}_c であるような系 (添え字 cc は質量 中心についての物理量であることを示す):

    L=Lc+MΣRc×vc,K=Kc+MΣvc2/2P=Pc+MΣvc.\begin{gathered} \boldsymbol{L}=\boldsymbol{L}_c+M_{\Sigma} \boldsymbol{R}_c \times \boldsymbol{v}_c, K=K_c+M_{\Sigma} v_c^2 / 2 \\ \boldsymbol{P}=\boldsymbol{P}_c+M_{\Sigma} \boldsymbol{v}_c . \end{gathered}

4.7: Steiner 定理

  1. Steiner の定理(平行軸の定理)も同じような形で は質量中心の回転軸からの距離):

    I=Ic+mb2I=I_c+m b^2

4.8: ポイント 6

  1. ポイント 6 の P\boldsymbol{P}L\boldsymbol{L} を用いて, Newton の第二法則 :

    FΣ=dP/dt,MΣ=dL/dt\boldsymbol{F}_{\Sigma}=\mathrm{d} \boldsymbol{P} / \mathrm{d} t, \boldsymbol{M}_{\Sigma}=\mathrm{d} \boldsymbol{L} / \mathrm{d} t

4.9: ポイント 5

  1. ポイント 5 にに加えて,質量中心を通る zz 軸に対する慣性モ一メントは Iz0=I_{z 0}= i,jmimj[(xixj)2+(yiyj)2]/(2MΣ)\sum_{i, j} m_i m_j\left[\left(x_i-x_j\right)^2+\left(y_i-y_j\right)^2\right] /\left(2 M_{\Sigma}\right)

4.10: 原点に対する慣性

  1. 原点に対する慣性モ一メント θ=miri2\theta=\sum m_i r_i^2 は, 2θ=Ix+Iy+Iz2 \theta=I_x+I_y+I_z を用いることで二次元物体や等 方性のある物体の IzI_z を計算するのに有用.

4.11: 相当単振子の長

  1. 相当単振子の長さが l~\tilde{l} である物理振子 :

    ω2(l)=g/(l+Ic/ml)ω(l)=ω(l~l)=g/l~,l~=l+Ic/ml\begin{aligned} & \omega^2(l)=g /\left(l+I_c / m l\right) \\ & \omega(l)=\omega(\tilde{l}-l)=\sqrt{g / \tilde{l}}, \quad \tilde{l}=l+I_c / m l \\ & \end{aligned}

4.12: 慣性モーメントの係数

  1. 慣性モーメントの係数 : 円柱 12\frac{1}{2}, 球 25\frac{2}{5}, 球殼 23\frac{2}{3}, 棒 112\frac{1}{12} (端に対しては 13\frac{1}{3} ), 正方形 16\frac{1}{6}.

4.13: よく使われる保存則

  1. よく使われる保存則:エネルギー(弾性衝突,摩擦な し), 運動量(正味の外力なし, 各方向について成立), 角運動量(正味の外トルクなし, 例えば, 外力のうでの 長さが 0 (これが 2 又は 3 点のまわりに成り立てば運 動量保存で代用できる))

4.14: 非慣性系における見かけの力

  1. 非慣性系における見かけの力 : 慣性力 ma-m a, 遠心力 mω2Rm \omega^2 \boldsymbol{R}, Coriolis 力 2mv×Ω2 m \boldsymbol{v} \times \Omega (避けた方がよい. 速 度に垂直なので仕事はしない).

4.15: 傾いた座標

  1. 傾いた座標:斜面上での運動については, 斜面に平行 と垂直な方向に軸をとるのがよい。このとき重力加速 度は xx 成分と yy 成分をもつ. 軸は斜交することもある が, v=vxex+vyey\boldsymbol{v}=v_x \boldsymbol{e}_x+v_y \boldsymbol{e}_y のとき vxv_xv\boldsymbol{v}xx 軸への射 影ではない.

4.16: 2 つの物体の衝突

  1. 2 つの物体の衝突 : 保存されるのは, a) 全運動量, b) 全角運動量,c) 一方の物体の衝突点に関する角運動量, d) 全エネルギー(弾性衝突の場合, 摩擦がある場合 は, 摩擦力に垂直な方向の運動エネルギーが保存される. e) 衝突中に滑りが止まったならば,接触点の最終 速度は接触面上にある. f) 滑りが止まらなかったなら ば, 一方の物体から他方に伝わる運動量は, 接触面の 法線と arctanμ\arctan \mu の角度をなす.

4.17: 剛体のすべての運動

  1. 剛体のすべての運動は (物体の各点の速度を見ると) 瞬 間回転中心 CC まわりの回転として表せる. 物体上の点 PPCC からの距離は PP の軌跡の曲率半径とは異なる ことに注意せよ.

4.18: 紐の張力

  1. 紐の張力:重さのある吊り紐では, 張力の水平成分は 一定で垂直成分は下にある紐の重さにより変わる. 滑 らかな面の上の紐による(単位長さあたりの)力は,そ の曲率半径と張力で決まり, N=T/RN=T / R. 似た場合と して, 表面張力による圧力は p=2σ/Rp=2 \sigma / R. 導出には直 径に沿った圧力を調ベる.

4.19: 液体の表面

  1. 液体の表面は(表面張力を無視すれば)等ポテンシャ ル面になる. 非圧縮性流体では, ww をポテンシャルエ ネルギーの体積密度として, p=P0wp=P_0-w.

4.20: 非圧縮性流体に対する Bernoulli の法則

  1. 非圧縮性流体に対する Bernoulli の法則:

    p+12ρv2+ρϕ= const. p+\frac{1}{2} \rho v^2+\rho \phi=\text { const. }

    一様な重力場では ϕ=gh\phi=g h. 比熱が cp[ J/kg]c_p[\mathrm{~J} / \mathrm{kg}] である気 体では,

    12v2+cpT= const. \frac{1}{2} v^2+c_p T=\text { const. }

4.21: 直線的な流線

  1. 直線的な流線に沾う運動量の連続性 : p+ρv2=p+\rho v^2= const.

4.22: 断熱不変量

  1. 断熱不変量 : 振動する系の 1 周期の間のパラメータの 相対的な変化が小さければ,位相空間( xpx-p 座標で表さ れる)上に書かれるループの面積は非常に高い精度で 保存される.

4.23: 安定性

  1. 安定性を調ベるには, a) ポテンシャルエネルギー最小 の原理,又は b) 仮想仕事の原理を用いる.

4.24: 空間的に有限な運動に対する Virial 定理

  1. 空間的に有限な運動に対する Virial 定理:a) もし FrF \propto|\boldsymbol{r}| ならば K=U\langle K\rangle=\langle U\rangle (時間平均). b) もし Fr2F \propto|\boldsymbol{r}|^{-2} ならば 2K=U2\langle K\rangle=-\langle U\rangle.

4.25: Tsiolkovsky 公式

  1. Tsiolkovsky の公式(ロケット): Δv=ulnMm\Delta v=u \ln \frac{M}{m}
]]>
<![CDATA[Formulas for IPhO 日本語版: Section 5 ]]> https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/5 https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/5 Thu, 01 Jul 2021 00:00:00 GMT Formulas for IPhO 日本語版: Section 5

5. 振動と波

5.1: 減衰振動

  1. 減衰振動:

    x¨+2γx˙+ω02x=0(γ<ω)\ddot{x}+2 \gamma \dot{x}+\omega_0^2 x=0(\gamma<\omega)

    この方程式の解は ((Section 1: #3)[1#_1-3-定数係数線形微分方程式] 参照) :

    x=x0eγtsin(tω02γ2φ0)x=x_0 e^{-\gamma t} \sin \left(t \sqrt{\omega_0^2-\gamma^2}-\varphi_0\right)

5.2: 連成振動の式

  1. 連成振動の式 : x¨i=jaijxj\ddot{x}_i=\sum_j a_{i j} x_j

5.3: 連成振動の系

  1. NN 個の連成振動の系は, すべての振動子が同じ振動数 ωi\omega_ixj=xj0sin(ωit+φij)x_j=x_{j 0} \sin \left(\omega_i t+\varphi_{i j}\right) のように振動するとい う固有モードを NN 個持つ. 固有振動数 ωiN\omega_i も N 個持 つ (一致するかもしれない, ωi=ωj\omega_i=\omega_j ). 一般解 (2N(2 N 個の積分定数 Xi,ϕiX_i, \phi_i を持つ) は全ての固有振動の重ね 合わせ :

    xj=iXixj0sin(ωit+φij+ϕi)x_j=\sum_i X_i x_{j 0} \sin \left(\omega_i t+\varphi_{i j}+\phi_i\right)

5.4: 一般化座標

  1. 一般化座標 ξ\xi ((Section 4: #4)[4#_4-4-一般化座標] 参照) で表され K=μξ˙2/2K=\mu \dot{\xi}^2 / 2 である系は, ξ=0\xi=0 の点で平衡. 小さな振動につ いて U(ξ)κξ2/2U(\xi) \approx \kappa \xi^2 / 2 (ここで κ=U(0))\left.\kappa=U^{\prime \prime}(0)\right) であり ω2=κ/μ\omega^2=\kappa / \mu.

5.5: 波の位相

  1. x,tx, t での波の位相は φ=kxωt+φ0\varphi=k x-\omega t+\varphi_0 で, k=2π/λk=2 \pi / \lambda は波数. x,tx, t での值は a0cosφ=Rea0eiφa_0 \cos \varphi=\operatorname{Re} a_0 e^{i \varphi}. 位相速 度は vf=νλ=ω/kv_f=\nu \lambda=\omega / k で, 群速度は vg=dω/dkv_g=\mathrm{d} \omega / \mathrm{d} k.

5.6: 線形波

  1. 線形波(電磁波, 小振幅の音波や水面波)の場合, どん なパルス波も正弦波の重ね合わせとして表せる. 定常 波は 2 つの逆向きに進む同じ波の合成 :

    ei(kxωt)+ei(kxωt)=2eiωtcoskte^{i(k x-\omega t)}+e^{i(-k x-\omega t)}=2 e^{-i \omega t} \cos k t

5.7: 気体中の音速

  1. 気体中の音速 :

    cs=(p/ρ)断熱 =γp/ρ=γv2/3c_s=\sqrt{(\partial p / \partial \rho)_{\text {断熱 }}}=\sqrt{\gamma p / \rho}=\sqrt{\gamma \overline{v^2} / 3}

5.8: 弾性体中の音速

  1. 弾性体中の音速は cs=E/ρc_s=\sqrt{E / \rho}.

5.9: 浅水波

  1. 浅水波 (hλ)(h \ll \lambda) の速さ: v=ghv=\sqrt{g h}. 弦の場合: v=T/ρlinv=\sqrt{T / \rho_{l i n}}.

5.10: Doppler 効果

  1. Doppler 効果 : ν=ν01+v/cs1u/cs\nu=\nu_0 \frac{1+v_{\|} / c_s}{1-u_{\|} / c_s}.

5.11: Huygens の原理

  1. Huygens の原理 : 波面は段階的に構成される. 過去 の波面のすべての点に仮想的な波源を置く. 結果は距 離 Δx=csΔt\Delta x=c_s \Delta t で区切られた曲線(ここで Δt\Delta t は時間 間隔, csc_s は与えられた点の速度). 波は波面に垂直に 進む.
]]>
Formulas for IPhO 日本語版: Section 5

5. 振動と波

5.1: 減衰振動

  1. 減衰振動:

    x¨+2γx˙+ω02x=0(γ<ω)\ddot{x}+2 \gamma \dot{x}+\omega_0^2 x=0(\gamma<\omega)

    この方程式の解は ((Section 1: #3)[1#_1-3-定数係数線形微分方程式] 参照) :

    x=x0eγtsin(tω02γ2φ0)x=x_0 e^{-\gamma t} \sin \left(t \sqrt{\omega_0^2-\gamma^2}-\varphi_0\right)

5.2: 連成振動の式

  1. 連成振動の式 : x¨i=jaijxj\ddot{x}_i=\sum_j a_{i j} x_j

5.3: 連成振動の系

  1. NN 個の連成振動の系は, すべての振動子が同じ振動数 ωi\omega_ixj=xj0sin(ωit+φij)x_j=x_{j 0} \sin \left(\omega_i t+\varphi_{i j}\right) のように振動するとい う固有モードを NN 個持つ. 固有振動数 ωiN\omega_i も N 個持 つ (一致するかもしれない, ωi=ωj\omega_i=\omega_j ). 一般解 (2N(2 N 個の積分定数 Xi,ϕiX_i, \phi_i を持つ) は全ての固有振動の重ね 合わせ :

    xj=iXixj0sin(ωit+φij+ϕi)x_j=\sum_i X_i x_{j 0} \sin \left(\omega_i t+\varphi_{i j}+\phi_i\right)

5.4: 一般化座標

  1. 一般化座標 ξ\xi ((Section 4: #4)[4#_4-4-一般化座標] 参照) で表され K=μξ˙2/2K=\mu \dot{\xi}^2 / 2 である系は, ξ=0\xi=0 の点で平衡. 小さな振動につ いて U(ξ)κξ2/2U(\xi) \approx \kappa \xi^2 / 2 (ここで κ=U(0))\left.\kappa=U^{\prime \prime}(0)\right) であり ω2=κ/μ\omega^2=\kappa / \mu.

5.5: 波の位相

  1. x,tx, t での波の位相は φ=kxωt+φ0\varphi=k x-\omega t+\varphi_0 で, k=2π/λk=2 \pi / \lambda は波数. x,tx, t での值は a0cosφ=Rea0eiφa_0 \cos \varphi=\operatorname{Re} a_0 e^{i \varphi}. 位相速 度は vf=νλ=ω/kv_f=\nu \lambda=\omega / k で, 群速度は vg=dω/dkv_g=\mathrm{d} \omega / \mathrm{d} k.

5.6: 線形波

  1. 線形波(電磁波, 小振幅の音波や水面波)の場合, どん なパルス波も正弦波の重ね合わせとして表せる. 定常 波は 2 つの逆向きに進む同じ波の合成 :

    ei(kxωt)+ei(kxωt)=2eiωtcoskte^{i(k x-\omega t)}+e^{i(-k x-\omega t)}=2 e^{-i \omega t} \cos k t

5.7: 気体中の音速

  1. 気体中の音速 :

    cs=(p/ρ)断熱 =γp/ρ=γv2/3c_s=\sqrt{(\partial p / \partial \rho)_{\text {断熱 }}}=\sqrt{\gamma p / \rho}=\sqrt{\gamma \overline{v^2} / 3}

5.8: 弾性体中の音速

  1. 弾性体中の音速は cs=E/ρc_s=\sqrt{E / \rho}.

5.9: 浅水波

  1. 浅水波 (hλ)(h \ll \lambda) の速さ: v=ghv=\sqrt{g h}. 弦の場合: v=T/ρlinv=\sqrt{T / \rho_{l i n}}.

5.10: Doppler 効果

  1. Doppler 効果 : ν=ν01+v/cs1u/cs\nu=\nu_0 \frac{1+v_{\|} / c_s}{1-u_{\|} / c_s}.

5.11: Huygens の原理

  1. Huygens の原理 : 波面は段階的に構成される. 過去 の波面のすべての点に仮想的な波源を置く. 結果は距 離 Δx=csΔt\Delta x=c_s \Delta t で区切られた曲線(ここで Δt\Delta t は時間 間隔, csc_s は与えられた点の速度). 波は波面に垂直に 進む.
]]>
<![CDATA[Formulas for IPhO 日本語版: Section 6 ]]> https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/6 https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/6 Thu, 01 Jul 2021 00:00:00 GMT Formulas for IPhO 日本語版: Section 6

6: 幾何光学,測光

6.1: Fermat 原理

  1. Fermat の原理 : 点 AA から BB への波の経路は波の移動 時間が最も短いもの.

6.2: Snell 法則

  1. Snell の法則 :

sinα1/sinα2=n2/n1=v1/v2.\sin \alpha_1 / \sin \alpha_2=n_2 / n_1=v_1 / v_2 .

6.3: 屈折率

  1. 屈折率が連続的に変化するならば,媒質を屈折率が nn で一定のいくつかの仮想的な層に分けて Snell の 法則を適用する. 光線は屈折率一定の層に沿って進む こともでき,もし全反射の条件をわずかに満たせば, n=n/r(rn^{\prime}=n / r \quad(r は曲率半径 ))

6.4: 屈折率な座標

  1. 屈折率が z\mathrm{z} 座標にのみ依存するならば, 光子の運動量 px,pyp_x, p_y とエネルギーは保存される:

kx,ky= const., k/n= const. k_x, k_y=\text { const., }|\boldsymbol{k}| / n=\text { const. }

6.5:薄いレンズの式

  1. 薄いレンズの式(符号に注意する):

1/a+1/b=1/fD1 / a+1 / b=1 / f \equiv D

6.6: Newton の式

  1. Newton の式 : 物体側焦点から物体までの距離を x1x_1, 像側焦点から像までの距離を x2x_2 とすると, x1x2=f2x_1 x_2=f^2

6.7: 像の位置を求める視差法

  1. 像の位置を求める視差法 : 目の位置と垂直に動かした ときに,鉛筆の先が像に対してずれないような位置を 探す.

6.8: レンズを通る光線の経路の幾何学的な描き方

  1. レンズを通る光線の経路の幾何学的な描き方:a) レン ズの中心を通る光線は屈折しない。b) 光軸に平行な光 線は焦点を通る,c) 屈折後, 初めに平行だった光線どうしは焦点面(焦点を通り光軸に垂直な平面)上で集 まる.d) 平面の像は平面であり,この 2 つの平面はレ ンズの平面上で交わる.

6.9: 光束

  1. 光束 Φ\Phi [単位: lumen (lm)(\operatorname{lm})] は, 光のエネルギー を示し, 眼の感度に応じて重み付けされる. 光度 [candela (cd)]は(光源から出る)立体角あたりの 光束で, I=Φ/ΩI=\Phi / \Omega. 照度 [lux(lx)][\operatorname{lux}(\mathrm{lx})] は(面に入射する) 面積あたりの光束で, E=Φ/SE=\Phi / S.

6.10: Gauss 定理

  1. 光束についての Gauss の定理 : 光度 IiI_i の点光源を囲 む閉曲面を通って外に出る光束は, Φ=4πIi\Phi=4 \pi \sum I_i. 光 源が 1 つで距離が rr のとき E=I/r2E=I / r^2

6.11: 実験のヒント

  1. 実験のヒント:紙についた油污れが周囲の紙と同じ明 るさならば,その紙は両面から同じように照らされて いる.
]]>
Formulas for IPhO 日本語版: Section 6

6: 幾何光学,測光

6.1: Fermat 原理

  1. Fermat の原理 : 点 AA から BB への波の経路は波の移動 時間が最も短いもの.

6.2: Snell 法則

  1. Snell の法則 :

sinα1/sinα2=n2/n1=v1/v2.\sin \alpha_1 / \sin \alpha_2=n_2 / n_1=v_1 / v_2 .

6.3: 屈折率

  1. 屈折率が連続的に変化するならば,媒質を屈折率が nn で一定のいくつかの仮想的な層に分けて Snell の 法則を適用する. 光線は屈折率一定の層に沿って進む こともでき,もし全反射の条件をわずかに満たせば, n=n/r(rn^{\prime}=n / r \quad(r は曲率半径 ))

6.4: 屈折率な座標

  1. 屈折率が z\mathrm{z} 座標にのみ依存するならば, 光子の運動量 px,pyp_x, p_y とエネルギーは保存される:

kx,ky= const., k/n= const. k_x, k_y=\text { const., }|\boldsymbol{k}| / n=\text { const. }

6.5:薄いレンズの式

  1. 薄いレンズの式(符号に注意する):

1/a+1/b=1/fD1 / a+1 / b=1 / f \equiv D

6.6: Newton の式

  1. Newton の式 : 物体側焦点から物体までの距離を x1x_1, 像側焦点から像までの距離を x2x_2 とすると, x1x2=f2x_1 x_2=f^2

6.7: 像の位置を求める視差法

  1. 像の位置を求める視差法 : 目の位置と垂直に動かした ときに,鉛筆の先が像に対してずれないような位置を 探す.

6.8: レンズを通る光線の経路の幾何学的な描き方

  1. レンズを通る光線の経路の幾何学的な描き方:a) レン ズの中心を通る光線は屈折しない。b) 光軸に平行な光 線は焦点を通る,c) 屈折後, 初めに平行だった光線どうしは焦点面(焦点を通り光軸に垂直な平面)上で集 まる.d) 平面の像は平面であり,この 2 つの平面はレ ンズの平面上で交わる.

6.9: 光束

  1. 光束 Φ\Phi [単位: lumen (lm)(\operatorname{lm})] は, 光のエネルギー を示し, 眼の感度に応じて重み付けされる. 光度 [candela (cd)]は(光源から出る)立体角あたりの 光束で, I=Φ/ΩI=\Phi / \Omega. 照度 [lux(lx)][\operatorname{lux}(\mathrm{lx})] は(面に入射する) 面積あたりの光束で, E=Φ/SE=\Phi / S.

6.10: Gauss 定理

  1. 光束についての Gauss の定理 : 光度 IiI_i の点光源を囲 む閉曲面を通って外に出る光束は, Φ=4πIi\Phi=4 \pi \sum I_i. 光 源が 1 つで距離が rr のとき E=I/r2E=I / r^2

6.11: 実験のヒント

  1. 実験のヒント:紙についた油污れが周囲の紙と同じ明 るさならば,その紙は両面から同じように照らされて いる.
]]>
<![CDATA[Formulas for IPhO 日本語版: Section 7 ]]> https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/7 https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/7 Thu, 01 Jul 2021 00:00:00 GMT Formulas for IPhO 日本語版: Section 7

7: 波動光学

7.1: Huygens の原理に基づいた回折

  1. Huygens の原理に基づいた回折 : 障害物が波面を切断 すると波面は小さな断片に分割され,それが仮想的な 点波源となり,観測点での波の振幅はこれらの波源か らの寄与の重ね合わせとなる.

7.2: 二重スリット

  1. 二重スリット(幅は da,λ)d \ll a, \lambda) による干渉:強 め合う角 φmax=arcsin(nλ/d),nZ.I\varphi_{\max }=\arcsin (n \lambda / d), n \in \mathbb{Z} . I \propto cos2(ka2sinφ),(k=2π/λ)\cos ^2\left(k \frac{a}{2} \sin \varphi\right),(k=2 \pi / \lambda)

7.3: 単スリット-弱め合う角

  1. 単スリット:弱め合う角: φmin =arcsin(nλ/d),n\varphi_{\text {min }}=\arcsin (n \lambda / d), n \in Z,n0\mathbb{Z}, n \neq 0. 中央の強め合う部分は n=±1n=\pm 1 の間である ことに注意せよ. Isin2(kd2sinφ)/sinφI \propto \sin ^2\left(k \frac{d}{2} \sin \varphi\right) / \sin \varphi

7.4: 回折格子

  1. 回折格子:主な強め合う角はポイント 2 と同じで, 主 な強め合う角の幅は dd を回折格子の正味の長さとすれ ばポイント 3 と同じ. nn 番目の明線のスペクトルの分 解能は,溝の総数を NN 本として λΔλ=nN\frac{\lambda}{\Delta \lambda}=n N.

7.5: 分光器の分解能

  1. 分光器の分解能 : 最短の光線と最長の光線の光学距離 の差を LL として, λΔλ=Lλ\frac{\lambda}{\Delta \lambda}=\frac{L}{\lambda}.

7.6: プリズムの分解能

  1. プリズムの分解能 :λΔλ=adn dλ: \frac{\lambda}{\Delta \lambda}=a \frac{\mathrm{d} n}{\mathrm{~d} \lambda}

7.7: 角度距離

  1. 理想的な望遠鏡 (レンズ) で 2 点を解像するときの角度距離 : φ1.22λ/d\varphi \approx 1.22 \lambda / d. この角度では, 一方の点の中 心が他方の点の最初の回折最小值に当たる.

7.8: Bragg の法則

  1. Bragg の法則:間隔が dd の平行な結晶面の組は, 2dsinθ=nλ2 d \sin \theta=n \lambda ならば X\mathrm{X} 線を反射する. ここで θ\theta は結 晶面と X 線がなす角 (かすめ角).

7.9: 高密度電体媒質反射

  1. 光学的に高密度な誘電体媒質による反射 : 位相が π\pi ず れる. 半透明の薄膜では ϕ+ϕ=π\phi_{\rightarrow}+\phi_{\leftarrow}=\pi. ここで ϕ\phi_{\rightarrow}ϕ\phi_{\leftarrow} は反射波と透過波の位相差(矢印は入射方向を 示す)

7.10: Fabry-Pérot 干渉計

  1. Fabry-Pérot 干渉計 : 高い反射率 r(1r1)r(1-r \ll 1) を持 つ 2 枚の平行な半透明の鏡. 分解能は νΔν2aλ(1r)\frac{\nu}{\Delta \nu} \approx \frac{2 a}{\lambda(1-r)}. 5 つの平面波 (干渉計の前で左右に進む波, 内部を左右 に進む波,後ろを進む波)を設定して境界条件を課す ことで,透過スペクトルを求められる.

7.11: コヒーレントな電磁波

  1. コヒーレントな電磁波: 電場をベクトル为で表し, ベク トル間の角度を位相差とする. 屈折率が n=n(ω)=n=n(\omega)= ε(ω)\sqrt{\varepsilon(\omega)} (普通 μ1\mu \approx 1 ) であることに注意せよ. エネ ルギー流密度(単位面積を通過する単位時間あたりの エネルギー): I=cnε0E2=cnμ0B2(EI=c n \varepsilon_0 E^2=\frac{c}{n \mu_0} B^2(EBB は実 効值)

7.12: Malus の法則

  1. Malus の法則 : 直線偏光が角度 φ\varphi で偏光板を通過する と I=I0cos2φI=I_0 \cos ^2 \varphi

7.13: 1/4 波長版

  1. 1/41 / 4 波長版 : 直線偏光成分間の位相が π/2\pi / 2 ずれる.

7.14: Brewster 角

  1. Brewster 角: 入射角が tanφ=n\tan \varphi=n を満たすとき, 反 射波と屈折波が垂直になり反射波は直線偏光となる.

7.15: 光学素子による回折

  1. 光学素子による回折 : レンズやプリズムなどを通る光 の光学距離を計算する必要はなく, 図形的に考える. 例えば,双プリズムは二重スリットによる回折と同じ 回折をする.

7.16: 光ファイバー

  1. 光ファイバー:Mach-Zehnder 干渉計は二重スリッ トによる干渉と, 円形共振器は Fabry-Pérot 干渉計 と似ている. Bragg フィルターは X\mathrm{X} 線の場合と同 じように働く. シングルモードの光ファイバーでは, Δn/n12(λ/d)2\Delta n / n \approx \frac{1}{2}(\lambda / d)^2.
]]>
Formulas for IPhO 日本語版: Section 7

7: 波動光学

7.1: Huygens の原理に基づいた回折

  1. Huygens の原理に基づいた回折 : 障害物が波面を切断 すると波面は小さな断片に分割され,それが仮想的な 点波源となり,観測点での波の振幅はこれらの波源か らの寄与の重ね合わせとなる.

7.2: 二重スリット

  1. 二重スリット(幅は da,λ)d \ll a, \lambda) による干渉:強 め合う角 φmax=arcsin(nλ/d),nZ.I\varphi_{\max }=\arcsin (n \lambda / d), n \in \mathbb{Z} . I \propto cos2(ka2sinφ),(k=2π/λ)\cos ^2\left(k \frac{a}{2} \sin \varphi\right),(k=2 \pi / \lambda)

7.3: 単スリット-弱め合う角

  1. 単スリット:弱め合う角: φmin =arcsin(nλ/d),n\varphi_{\text {min }}=\arcsin (n \lambda / d), n \in Z,n0\mathbb{Z}, n \neq 0. 中央の強め合う部分は n=±1n=\pm 1 の間である ことに注意せよ. Isin2(kd2sinφ)/sinφI \propto \sin ^2\left(k \frac{d}{2} \sin \varphi\right) / \sin \varphi

7.4: 回折格子

  1. 回折格子:主な強め合う角はポイント 2 と同じで, 主 な強め合う角の幅は dd を回折格子の正味の長さとすれ ばポイント 3 と同じ. nn 番目の明線のスペクトルの分 解能は,溝の総数を NN 本として λΔλ=nN\frac{\lambda}{\Delta \lambda}=n N.

7.5: 分光器の分解能

  1. 分光器の分解能 : 最短の光線と最長の光線の光学距離 の差を LL として, λΔλ=Lλ\frac{\lambda}{\Delta \lambda}=\frac{L}{\lambda}.

7.6: プリズムの分解能

  1. プリズムの分解能 :λΔλ=adn dλ: \frac{\lambda}{\Delta \lambda}=a \frac{\mathrm{d} n}{\mathrm{~d} \lambda}

7.7: 角度距離

  1. 理想的な望遠鏡 (レンズ) で 2 点を解像するときの角度距離 : φ1.22λ/d\varphi \approx 1.22 \lambda / d. この角度では, 一方の点の中 心が他方の点の最初の回折最小值に当たる.

7.8: Bragg の法則

  1. Bragg の法則:間隔が dd の平行な結晶面の組は, 2dsinθ=nλ2 d \sin \theta=n \lambda ならば X\mathrm{X} 線を反射する. ここで θ\theta は結 晶面と X 線がなす角 (かすめ角).

7.9: 高密度電体媒質反射

  1. 光学的に高密度な誘電体媒質による反射 : 位相が π\pi ず れる. 半透明の薄膜では ϕ+ϕ=π\phi_{\rightarrow}+\phi_{\leftarrow}=\pi. ここで ϕ\phi_{\rightarrow}ϕ\phi_{\leftarrow} は反射波と透過波の位相差(矢印は入射方向を 示す)

7.10: Fabry-Pérot 干渉計

  1. Fabry-Pérot 干渉計 : 高い反射率 r(1r1)r(1-r \ll 1) を持 つ 2 枚の平行な半透明の鏡. 分解能は νΔν2aλ(1r)\frac{\nu}{\Delta \nu} \approx \frac{2 a}{\lambda(1-r)}. 5 つの平面波 (干渉計の前で左右に進む波, 内部を左右 に進む波,後ろを進む波)を設定して境界条件を課す ことで,透過スペクトルを求められる.

7.11: コヒーレントな電磁波

  1. コヒーレントな電磁波: 電場をベクトル为で表し, ベク トル間の角度を位相差とする. 屈折率が n=n(ω)=n=n(\omega)= ε(ω)\sqrt{\varepsilon(\omega)} (普通 μ1\mu \approx 1 ) であることに注意せよ. エネ ルギー流密度(単位面積を通過する単位時間あたりの エネルギー): I=cnε0E2=cnμ0B2(EI=c n \varepsilon_0 E^2=\frac{c}{n \mu_0} B^2(EBB は実 効值)

7.12: Malus の法則

  1. Malus の法則 : 直線偏光が角度 φ\varphi で偏光板を通過する と I=I0cos2φI=I_0 \cos ^2 \varphi

7.13: 1/4 波長版

  1. 1/41 / 4 波長版 : 直線偏光成分間の位相が π/2\pi / 2 ずれる.

7.14: Brewster 角

  1. Brewster 角: 入射角が tanφ=n\tan \varphi=n を満たすとき, 反 射波と屈折波が垂直になり反射波は直線偏光となる.

7.15: 光学素子による回折

  1. 光学素子による回折 : レンズやプリズムなどを通る光 の光学距離を計算する必要はなく, 図形的に考える. 例えば,双プリズムは二重スリットによる回折と同じ 回折をする.

7.16: 光ファイバー

  1. 光ファイバー:Mach-Zehnder 干渉計は二重スリッ トによる干渉と, 円形共振器は Fabry-Pérot 干渉計 と似ている. Bragg フィルターは X\mathrm{X} 線の場合と同 じように働く. シングルモードの光ファイバーでは, Δn/n12(λ/d)2\Delta n / n \approx \frac{1}{2}(\lambda / d)^2.
]]>
<![CDATA[Formulas for IPhO 日本語版: Section 8 ]]> https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/8 https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/8 Thu, 01 Jul 2021 00:00:00 GMT Formulas for IPhO 日本語版: Section 8

8: 電気回路

8.1: V=I R, P=V I

  1. V=IR,P=VIV=I R, P=V I

    R直列 =Ri,R並列 1=Ri1R_{\text {直列 }}=\sum R_i, R_{\text {並列 }}^{-1}=\sum R_i^{-1}

8.2: Kirchhoff の法則

  1. Kirchhoff の法則 :

     節点 I=0,閉路 V=0\sum_{\substack{\text { 節点 }}} I=0, \sum_{\text {閉路 }} V=0

8.3: ポイント 2 の方程式を減らすために

  1. ポイント 2 の方程式を減らすために: 節点電位法. ルー プ電流法. 等価回路 (3 端子の場合 \Rightarrow \triangle 又YY の形, 起電力のある 2 端子の場合 \Rightarrow 抵抗と電池の直列)

8.4: 無限につながる抵抗

  1. 無限につながる抵抗 : 無限に続く格子の隣り合う節点 間で,自己相似性を使う。鏡像法の一般化された方法.

8.5: 交流回路

  1. 交流回路: RRZZ に置き換えてポイント 141 \sim 4 を用 いる.

    ZR=R,ZC=1/iωC,ZL=iωLφ=argZ,Veff =ZIeff P=VIcos(argZ)=Ii2Ri\begin{gathered} Z_R=R, Z_C=1 / i \omega C, Z_L=i \omega L \\ \varphi=\arg Z, V_{\text {eff }}=|Z| I_{\text {eff }} \\ P=|V||I| \cos (\arg Z)=\sum I_i^2 R_i \end{gathered}

8.6: 特性時間

  1. 特性時間: τRC=RC,τLR=L/R.ωLC=\tau_{R C}=R C, \tau_{L R}=L / R . \omega_{L C}= 1/LC1 / \sqrt{L C}. 定常的な電流分布への緩和は指数関数的で et/τ\propto e^{-t / \tau}

8.7: 電気回路のエネルギー保存則

  1. 電気回路のエネルギー保存則 : ΔW+Q=qV\Delta W+Q=q V. ここ で qq は電圧降下 VV を通った電気量で, 電源のする仕事 は A=qVemfA=q V_{\mathrm{emf}}

8.8: コンデンサーの位置エネルギー式

  1. コンデンサーの位置エネルギー式: WC=CV2/2,WL=LI2/2W_C=C V^2 / 2, W_L=L I^2 / 2.

8.9: 磁束密度

  1. Vemf=dΦ/dt=d(LI)/dt,Φ=BSV_{\mathrm{emf}}=-\mathrm{d} \Phi / \mathrm{d} t=\mathrm{d}(L I) / \mathrm{d} t, \Phi=B S.

8.10: 非線形素子

  1. 非 線形素子: VIV-I グラフでの非線形曲線と Ohm/Kirchhoff の法則を表す直線との交点として 为形的に解を求める. 複数の交点があれば安定性を調 ベる. いくつかの解は普通安定でない.

8.11: 短時間と長時間の極限を利用

  1. 短時間と長時間の極限を利用する: tobservation t_{\text {observation }} \gg τRC\tau_{R C} or τLR\tau_{L R} ならば, IC0(CI_C \approx 0(C は断線している)又 は VL0V_L \approx 0 ( LL は短絡している)のような準平衡状態に 達する. tobservation τRCt_{\text {observation }} \ll \tau_{R C} or τLR\tau_{L R} ならば, CC の電 気量の変化や LL での電流の変化は小さく, ΔQQ\Delta Q \ll QΔII\Delta I \ll I. 即ち CC は短絡していて LL は断線して いる.

8.12: 推論

  1. L0L \neq 0 ならば, I(t)I(t) は連続.

8.13: 超電導の回路

  1. 超電導の回路について, 磁束 Φ=\Phi= const.. 特に, 外部 磁場が無ければ LI=L I= const.

8.14: 相互誘導

  1. 相互誘導 : 回路 1 を通る磁束は Φ1=L1I1+L12I2\Phi_1=L_1 I_1+L_{12} I_2 ( I2I_2 は回路 2 を流れる電流) で, L12=L21ML_{12}=L_{21} \equiv MML1L2M \leq \sqrt{L_1 L_2} が成立.
]]>
Formulas for IPhO 日本語版: Section 8

8: 電気回路

8.1: V=I R, P=V I

  1. V=IR,P=VIV=I R, P=V I

    R直列 =Ri,R並列 1=Ri1R_{\text {直列 }}=\sum R_i, R_{\text {並列 }}^{-1}=\sum R_i^{-1}

8.2: Kirchhoff の法則

  1. Kirchhoff の法則 :

     節点 I=0,閉路 V=0\sum_{\substack{\text { 節点 }}} I=0, \sum_{\text {閉路 }} V=0

8.3: ポイント 2 の方程式を減らすために

  1. ポイント 2 の方程式を減らすために: 節点電位法. ルー プ電流法. 等価回路 (3 端子の場合 \Rightarrow \triangle 又YY の形, 起電力のある 2 端子の場合 \Rightarrow 抵抗と電池の直列)

8.4: 無限につながる抵抗

  1. 無限につながる抵抗 : 無限に続く格子の隣り合う節点 間で,自己相似性を使う。鏡像法の一般化された方法.

8.5: 交流回路

  1. 交流回路: RRZZ に置き換えてポイント 141 \sim 4 を用 いる.

    ZR=R,ZC=1/iωC,ZL=iωLφ=argZ,Veff =ZIeff P=VIcos(argZ)=Ii2Ri\begin{gathered} Z_R=R, Z_C=1 / i \omega C, Z_L=i \omega L \\ \varphi=\arg Z, V_{\text {eff }}=|Z| I_{\text {eff }} \\ P=|V||I| \cos (\arg Z)=\sum I_i^2 R_i \end{gathered}

8.6: 特性時間

  1. 特性時間: τRC=RC,τLR=L/R.ωLC=\tau_{R C}=R C, \tau_{L R}=L / R . \omega_{L C}= 1/LC1 / \sqrt{L C}. 定常的な電流分布への緩和は指数関数的で et/τ\propto e^{-t / \tau}

8.7: 電気回路のエネルギー保存則

  1. 電気回路のエネルギー保存則 : ΔW+Q=qV\Delta W+Q=q V. ここ で qq は電圧降下 VV を通った電気量で, 電源のする仕事 は A=qVemfA=q V_{\mathrm{emf}}

8.8: コンデンサーの位置エネルギー式

  1. コンデンサーの位置エネルギー式: WC=CV2/2,WL=LI2/2W_C=C V^2 / 2, W_L=L I^2 / 2.

8.9: 磁束密度

  1. Vemf=dΦ/dt=d(LI)/dt,Φ=BSV_{\mathrm{emf}}=-\mathrm{d} \Phi / \mathrm{d} t=\mathrm{d}(L I) / \mathrm{d} t, \Phi=B S.

8.10: 非線形素子

  1. 非 線形素子: VIV-I グラフでの非線形曲線と Ohm/Kirchhoff の法則を表す直線との交点として 为形的に解を求める. 複数の交点があれば安定性を調 ベる. いくつかの解は普通安定でない.

8.11: 短時間と長時間の極限を利用

  1. 短時間と長時間の極限を利用する: tobservation t_{\text {observation }} \gg τRC\tau_{R C} or τLR\tau_{L R} ならば, IC0(CI_C \approx 0(C は断線している)又 は VL0V_L \approx 0 ( LL は短絡している)のような準平衡状態に 達する. tobservation τRCt_{\text {observation }} \ll \tau_{R C} or τLR\tau_{L R} ならば, CC の電 気量の変化や LL での電流の変化は小さく, ΔQQ\Delta Q \ll QΔII\Delta I \ll I. 即ち CC は短絡していて LL は断線して いる.

8.12: 推論

  1. L0L \neq 0 ならば, I(t)I(t) は連続.

8.13: 超電導の回路

  1. 超電導の回路について, 磁束 Φ=\Phi= const.. 特に, 外部 磁場が無ければ LI=L I= const.

8.14: 相互誘導

  1. 相互誘導 : 回路 1 を通る磁束は Φ1=L1I1+L12I2\Phi_1=L_1 I_1+L_{12} I_2 ( I2I_2 は回路 2 を流れる電流) で, L12=L21ML_{12}=L_{21} \equiv MML1L2M \leq \sqrt{L_1 L_2} が成立.
]]>
<![CDATA[Formulas for IPhO 日本語版: Section 9 ]]> https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/9 https://note.toshiki.dev/academic/physics/ipho-formulas-jpn/9 Thu, 01 Jul 2021 00:00:00 GMT Formulas for IPhO 日本語版: Section 9

9: 電磁気学

9.1: Coulomb の法則

  1. F=kq1q2/r2,U=kq1q2/rF=k q_1 q_2 / r^2, U=k q_1 q_2 / r で, Kepler の法則が 使える (Section 12 参照).

9.2: Gauss の法則

  1. Gauss の法則 : BdS=0\oint \boldsymbol{B} \cdot \mathrm{d} \boldsymbol{S}=0,

    εEdS=Q,gdS=4πGM\oint \varepsilon \boldsymbol{E} \cdot \mathrm{d} \boldsymbol{S}=Q, \oint \boldsymbol{g} \cdot \mathrm{d} \boldsymbol{S}=-4 \pi G M

9.3: 循環定理

  1. 循環定理 :

    Edl=0(=Φ˙),Bdlμ=I,gdl=0\oint \boldsymbol{E} \cdot \mathrm{d} \boldsymbol{l}=0(=\dot{\Phi}), \oint \frac{\boldsymbol{B} \cdot \mathrm{d} \boldsymbol{l}}{\mu}=I, \oint \boldsymbol{g} \cdot \mathrm{d} \boldsymbol{l}=0

9.4: 電流素片により生じる磁束密度

  1. 電流素片により生じる磁束密度 :

    dB=μI4πdl×err2.\mathrm{d} \boldsymbol{B}=\frac{\mu I}{4 \pi} \frac{\mathrm{d} \boldsymbol{l} \times \boldsymbol{e}_r}{r^2} .

    したがって電流 II が流れる円形回路の中心では B=μ0I2rB=\frac{\mu_0 I}{2 r}.

9.5: ローレンツ力

  1. F=e(E+v×B),F=I×Bl\boldsymbol{F}=e(\boldsymbol{E}+\boldsymbol{v} \times \boldsymbol{B}), \boldsymbol{F}=\boldsymbol{I} \times \boldsymbol{B} l.

9.6: Gauss の定理と循環定理より

  1. Gauss の定理と循環定理より:帯電した導線について E=σ2πε0rE=\frac{\sigma}{2 \pi \varepsilon_0 r}, 電流が流れる導線について B=μ0I2πrB=\frac{\mu_0 I}{2 \pi r}. 帯電した面について E=σ2ε0E=\frac{\sigma}{2 \varepsilon_0}, 電流が流れる面につい て B=μ0i2B=\frac{\mu_0 i}{2}. 一様に帯電した球殼(又は無限に長い円 筒)の内部で E=0E=0, 軸に沿って表面に電流が流れる 円筒の内部で B=0B=0. 密度 ρ\rho で一様に帯電, 又は一様 な電流 i\boldsymbol{i} が流れる, 球 (d=3)/(d=3) / 円柱 (d2)/(d-2) / 平面 (d=1)(d=1) の内部で,

    E=ρεdr,B=1μdi×r\boldsymbol{E}=\frac{\rho}{\varepsilon d} \boldsymbol{r}, \boldsymbol{B}=\frac{1}{\mu d} \boldsymbol{i} \times \boldsymbol{r}

9.7: 長いソレノイド

  1. 長いソレノイド: 内部で B=μnIB=\mu n I, 外部で B=0B=0. 磁束 Φ=NBS(n=Nl)\Phi=N B S\left(n=\frac{N}{l}\right). インダクタンス L=L= Φ/I=μn2V\Phi / I=\mu n^2 V. 短いソレノイド :B=μnIΩ4π(Ω: B_{\|}=\frac{\mu n I \Omega}{4 \pi}(\Omega は 立体角).

9.8: 磁場を小型コイルや衝撃検流計で測定する

  1. 磁場を小型コイルや衝撃検流計で測定する: q=q= VR dt=NSΔB/R\int \frac{V}{R} \mathrm{~d} t=N S \Delta B / R.

9.9: 静電場のエネルギー

  1. 静電場のエネルギー:

    U=ki<jqiqjrij=12ϕ(r)dq, dq=ρ(r)dVU=k \sum_{i<j} \frac{q_i q_j}{r_{i j}}=\frac{1}{2} \int \phi(\boldsymbol{r}) \mathrm{d} q, \mathrm{~d} q=\rho(\boldsymbol{r}) \mathrm{d} V

9.10: 一様に帯電した球面や円筒面の各部分の間に働く力

  1. 一様に帯電した球面や円筒面の各部分の間に働く力 : 帯電による力を静水圧による力に置き換える.

9.11: 全ての電荷

  1. 全ての電荷が距離 rr にある場合(例えば,不均一に帯 電した球やリングの中心) ϕϕ=kQ/r\phi \phi=k Q / r

9.12: 外部電荷

  1. 外部電荷によって引き起こされる正味の電荷(又は電 位)を求めるには, 電荷を「出現」させて問題を対称的 にし,重ね合わせの原理を用いる.

9.14: 導体

  1. 導体は電荷や電場を遮蔽する.例えば,中空の球体の 内部の電荷分布は外から見えない(あたかも QQ という 電荷を持った導電性の球があるように見える).

9.15: 静電容量

  1. 静電容量: C=εS/dC=\varepsilon S / d (平板), 4πεr4 \pi \varepsilon r (球), 2πεl(lnR/r)12 \pi \varepsilon l(\ln R / r)^{-1} (同軸円筒).

9.16: 双極子モーメント

  1. 双極子モーメント:

    pe=qiri=qd,pμ=IS\boldsymbol{p}_e=\sum q_i \boldsymbol{r}_i=q \boldsymbol{d}, \boldsymbol{p}_\mu=I \boldsymbol{S}

9.17: 双極子場

  1. 双極子場 : ϕ=kper/r2,E,Br3\phi=k \boldsymbol{p} \cdot \boldsymbol{e}_r / r^2, E, B \propto r^{-3}

9.18: 双極子に働く力

  1. 双極子に働く力 : F=(peE),F=(pμB)F=\left(\boldsymbol{p}_e \cdot \boldsymbol{E}\right)^{\prime}, F=\left(\boldsymbol{p}_\mu \cdot \boldsymbol{B}\right)^{\prime} [訳 者注 : ここの微分はむしろ grad\operatorname{grad} である]. 2 つの双極 子間の相互作用 :Fr4: F \propto r^{-4}.

9.19: 磁気双極子としての点電荷

  1. 磁気双極子としての点電荷 : pμΦv2/Bp_\mu \propto \Phi \propto v_{\perp}^2 / B は断熱 不変量 (Section 4: #22 参照).

9.20: 鏡像法

  1. 鏡像法 : 接地された(磁石の場合は超電導の)平面が鏡 の役割をする. 接地された(又は孤立した)球体の場 は, 球体の内部にある 1 つ(又は 2 つ)の架空の電荷 のつくる場として求められる. 平面導波管(金属板の 間のスリット)内の場は, 電磁平面波の重ね合わせと して求められる.

9.21: 一様(電)場中の球 (円柱) の分極

  1. 一様(電)場中の球 (円柱) の分極 : (+ρ(+\rhoρ-\rho に一 様に帯電した球 (円柱) の重ね合わせで, dEd \propto E.

9.22: 渦電流

  1. 渦電流: 電流損失密度 B2v2/ρ.1\approx B^2 v^2 / \rho .1 回の通過で与え られる運動量 : FτB2a3d/ρF \tau \approx B^2 a^3 d / \rho (ここで dd は厚さ, aa は大きさ).
]]>
Formulas for IPhO 日本語版: Section 9

9: 電磁気学

9.1: Coulomb の法則

  1. F=kq1q2/r2,U=kq1q2/rF=k q_1 q_2 / r^2, U=k q_1 q_2 / r で, Kepler の法則が 使える (Section 12 参照).

9.2: Gauss の法則

  1. Gauss の法則 : BdS=0\oint \boldsymbol{B} \cdot \mathrm{d} \boldsymbol{S}=0,

    εEdS=Q,gdS=4πGM\oint \varepsilon \boldsymbol{E} \cdot \mathrm{d} \boldsymbol{S}=Q, \oint \boldsymbol{g} \cdot \mathrm{d} \boldsymbol{S}=-4 \pi G M

9.3: 循環定理

  1. 循環定理 :

    Edl=0(=Φ˙),Bdlμ=I,gdl=0\oint \boldsymbol{E} \cdot \mathrm{d} \boldsymbol{l}=0(=\dot{\Phi}), \oint \frac{\boldsymbol{B} \cdot \mathrm{d} \boldsymbol{l}}{\mu}=I, \oint \boldsymbol{g} \cdot \mathrm{d} \boldsymbol{l}=0

9.4: 電流素片により生じる磁束密度

  1. 電流素片により生じる磁束密度 :

    dB=μI4πdl×err2.\mathrm{d} \boldsymbol{B}=\frac{\mu I}{4 \pi} \frac{\mathrm{d} \boldsymbol{l} \times \boldsymbol{e}_r}{r^2} .

    したがって電流 II が流れる円形回路の中心では B=μ0I2rB=\frac{\mu_0 I}{2 r}.

9.5: ローレンツ力

  1. F=e(E+v×B),F=I×Bl\boldsymbol{F}=e(\boldsymbol{E}+\boldsymbol{v} \times \boldsymbol{B}), \boldsymbol{F}=\boldsymbol{I} \times \boldsymbol{B} l.

9.6: Gauss の定理と循環定理より

  1. Gauss の定理と循環定理より:帯電した導線について E=σ2πε0rE=\frac{\sigma}{2 \pi \varepsilon_0 r}, 電流が流れる導線について B=μ0I2πrB=\frac{\mu_0 I}{2 \pi r}. 帯電した面について E=σ2ε0E=\frac{\sigma}{2 \varepsilon_0}, 電流が流れる面につい て B=μ0i2B=\frac{\mu_0 i}{2}. 一様に帯電した球殼(又は無限に長い円 筒)の内部で E=0E=0, 軸に沿って表面に電流が流れる 円筒の内部で B=0B=0. 密度 ρ\rho で一様に帯電, 又は一様 な電流 i\boldsymbol{i} が流れる, 球 (d=3)/(d=3) / 円柱 (d2)/(d-2) / 平面 (d=1)(d=1) の内部で,

    E=ρεdr,B=1μdi×r\boldsymbol{E}=\frac{\rho}{\varepsilon d} \boldsymbol{r}, \boldsymbol{B}=\frac{1}{\mu d} \boldsymbol{i} \times \boldsymbol{r}

9.7: 長いソレノイド

  1. 長いソレノイド: 内部で B=μnIB=\mu n I, 外部で B=0B=0. 磁束 Φ=NBS(n=Nl)\Phi=N B S\left(n=\frac{N}{l}\right). インダクタンス L=L= Φ/I=μn2V\Phi / I=\mu n^2 V. 短いソレノイド :B=μnIΩ4π(Ω: B_{\|}=\frac{\mu n I \Omega}{4 \pi}(\Omega は 立体角).

9.8: 磁場を小型コイルや衝撃検流計で測定する

  1. 磁場を小型コイルや衝撃検流計で測定する: q=q= VR dt=NSΔB/R\int \frac{V}{R} \mathrm{~d} t=N S \Delta B / R.

9.9: 静電場のエネルギー

  1. 静電場のエネルギー:

    U=ki<jqiqjrij=12ϕ(r)dq, dq=ρ(r)dVU=k \sum_{i<j} \frac{q_i q_j}{r_{i j}}=\frac{1}{2} \int \phi(\boldsymbol{r}) \mathrm{d} q, \mathrm{~d} q=\rho(\boldsymbol{r}) \mathrm{d} V

9.10: 一様に帯電した球面や円筒面の各部分の間に働く力

  1. 一様に帯電した球面や円筒面の各部分の間に働く力 : 帯電による力を静水圧による力に置き換える.

9.11: 全ての電荷

  1. 全ての電荷が距離 rr にある場合(例えば,不均一に帯 電した球やリングの中心) ϕϕ=kQ/r\phi \phi=k Q / r

9.12: 外部電荷

  1. 外部電荷によって引き起こされる正味の電荷(又は電 位)を求めるには, 電荷を「出現」させて問題を対称的 にし,重ね合わせの原理を用いる.

9.14: 導体

  1. 導体は電荷や電場を遮蔽する.例えば,中空の球体の 内部の電荷分布は外から見えない(あたかも QQ という 電荷を持った導電性の球があるように見える).

9.15: 静電容量

  1. 静電容量: C=εS/dC=\varepsilon S / d (平板), 4πεr4 \pi \varepsilon r (球), 2πεl(lnR/r)12 \pi \varepsilon l(\ln R / r)^{-1} (同軸円筒).

9.16: 双極子モーメント

  1. 双極子モーメント:

    pe=qiri=qd,pμ=IS\boldsymbol{p}_e=\sum q_i \boldsymbol{r}_i=q \boldsymbol{d}, \boldsymbol{p}_\mu=I \boldsymbol{S}

9.17: 双極子場

  1. 双極子場 : ϕ=kper/r2,E,Br3\phi=k \boldsymbol{p} \cdot \boldsymbol{e}_r / r^2, E, B \propto r^{-3}

9.18: 双極子に働く力

  1. 双極子に働く力 : F=(peE),F=(pμB)F=\left(\boldsymbol{p}_e \cdot \boldsymbol{E}\right)^{\prime}, F=\left(\boldsymbol{p}_\mu \cdot \boldsymbol{B}\right)^{\prime} [訳 者注 : ここの微分はむしろ grad\operatorname{grad} である]. 2 つの双極 子間の相互作用 :Fr4: F \propto r^{-4}.

9.19: 磁気双極子としての点電荷

  1. 磁気双極子としての点電荷 : pμΦv2/Bp_\mu \propto \Phi \propto v_{\perp}^2 / B は断熱 不変量 (Section 4: #22 参照).

9.20: 鏡像法

  1. 鏡像法 : 接地された(磁石の場合は超電導の)平面が鏡 の役割をする. 接地された(又は孤立した)球体の場 は, 球体の内部にある 1 つ(又は 2 つ)の架空の電荷 のつくる場として求められる. 平面導波管(金属板の 間のスリット)内の場は, 電磁平面波の重ね合わせと して求められる.

9.21: 一様(電)場中の球 (円柱) の分極

  1. 一様(電)場中の球 (円柱) の分極 : (+ρ(+\rhoρ-\rho に一 様に帯電した球 (円柱) の重ね合わせで, dEd \propto E.

9.22: 渦電流

  1. 渦電流: 電流損失密度 B2v2/ρ.1\approx B^2 v^2 / \rho .1 回の通過で与え られる運動量 : FτB2a3d/ρF \tau \approx B^2 a^3 d / \rho (ここで dd は厚さ, aa は大きさ).
]]>
<![CDATA[2023-2-27: Vocabulary]]> https://note.toshiki.dev/academic/vocabulary/2023/02/2023-02-27 https://note.toshiki.dev/academic/vocabulary/2023/02/2023-02-27 Thu, 01 Jul 2021 00:00:00 GMT 2023-2-27: Vocabulary

This table of vocabularies are from "Sadlier Vocabulary Workshop-Level G (Unit 4)" with their corresponding textbook definitions and part of speeches (from some of them) made into a collection.

Vocabulary Definition
Atrophy (n.) the wasting away of a body organ or tissue; any progressive decline or failure; (v.) to waste away
Bastion A fortified place, stronghold
Concord A state of agreement, harmony, unanimity; a treaty, pact, covenant
Consummate (adj.) complete or perfect in the highest degree; (v.) to bring to a state of completion or perfection
Disarray (n.) disorder, confusion; (v.) to throw into disorder
Exigency Urgency, pressure; urgent demand, pressing need; an emergency
Flotsam Floating debris; homeless, impoverished people
Frenetic Frenzied, highly agitated
Glean To gather bit by bit; to gather small quantities of grain left in a field by the reapers.
Grouse (n.) A type of game bird; a complaint; (v.) to complain, grumble
Incarcerate To imprison, confine, jail
Incumbent (adj.) obligatory, required; (n.) one who holds a specific office at the time spoken of
Jocular Humorous, jesting, jolly, joking
Ludicrous Ridiculous, laughable, absurd
Mordant Biting or caustic in thought, manner, or style; sharply or bitterly harsh.
Nettle (n.) a prickly or stinging plant; (v.) to arouse displeasure, impatience, or anger; to vex or irritate severely
Pecuniary Consisting of or measured in money; of or related to money
Pusillanimous Contemptibly cowardly or mean-spirited
Recumbent In a reclining position, lying down, in the posture of one sleeping or resting.
Stratagem A scheme to outwit or deceive an opponent or to gain and end.

Reference

]]>
2023-2-27: Vocabulary

This table of vocabularies are from "Sadlier Vocabulary Workshop-Level G (Unit 4)" with their corresponding textbook definitions and part of speeches (from some of them) made into a collection.

Vocabulary Definition
Atrophy (n.) the wasting away of a body organ or tissue; any progressive decline or failure; (v.) to waste away
Bastion A fortified place, stronghold
Concord A state of agreement, harmony, unanimity; a treaty, pact, covenant
Consummate (adj.) complete or perfect in the highest degree; (v.) to bring to a state of completion or perfection
Disarray (n.) disorder, confusion; (v.) to throw into disorder
Exigency Urgency, pressure; urgent demand, pressing need; an emergency
Flotsam Floating debris; homeless, impoverished people
Frenetic Frenzied, highly agitated
Glean To gather bit by bit; to gather small quantities of grain left in a field by the reapers.
Grouse (n.) A type of game bird; a complaint; (v.) to complain, grumble
Incarcerate To imprison, confine, jail
Incumbent (adj.) obligatory, required; (n.) one who holds a specific office at the time spoken of
Jocular Humorous, jesting, jolly, joking
Ludicrous Ridiculous, laughable, absurd
Mordant Biting or caustic in thought, manner, or style; sharply or bitterly harsh.
Nettle (n.) a prickly or stinging plant; (v.) to arouse displeasure, impatience, or anger; to vex or irritate severely
Pecuniary Consisting of or measured in money; of or related to money
Pusillanimous Contemptibly cowardly or mean-spirited
Recumbent In a reclining position, lying down, in the posture of one sleeping or resting.
Stratagem A scheme to outwit or deceive an opponent or to gain and end.

Reference

]]>
<![CDATA[Welcome to My Vocabulary List! ]]> https://note.toshiki.dev/academic/vocabulary/ https://note.toshiki.dev/academic/vocabulary/ Thu, 01 Jul 2021 00:00:00 GMT Welcome to My Vocabulary List! ]]> Welcome to My Vocabulary List! ]]> <![CDATA[@andatoshiki/markdown-it-katex]]> https://note.toshiki.dev/application/markdown-it-katex/how-to-use https://note.toshiki.dev/application/markdown-it-katex/how-to-use Thu, 01 Jul 2021 00:00:00 GMT @andatoshiki/markdown-it-katex

Add graceful KaTeX\KaTeX rendering to your Markdown like a charm with markdown-it plugin.

1: Installation

Before you start using this plugin, make sure you have already installed the default markdown-it parser; if not, please run the following command or refer to the official markdown-it documentation.

sh
$ npm install markdown-it --save
$ npm install markdown-it --save

First install package with your preferred package manager (npm, yarn, pnpm), or include javascript before the closing </body> for markdown-it-katex's core utils to be loaded for the static page.

sh
$ npm install -D @andatoshiki/markdown-it-katex
$ npm install -D @andatoshiki/markdown-it-katex
sh
$ yarn add --dev @andatoshiki/markdown-it-katex
$ yarn add --dev @andatoshiki/markdown-it-katex
sh
$ pnpm add -D @andatoshiki/markdown-it-katex
$ pnpm add -D @andatoshiki/markdown-it-katex
html
<!-- your other body contents ... -->
    <script src="https://unpkg.com/@andatoshiki/markdown-it-katex@0.0.3/markdown-it-katex.min.js"></script>
</body>
<!-- your other body contents ... -->
    <script src="https://unpkg.com/@andatoshiki/markdown-it-katex@0.0.3/markdown-it-katex.min.js"></script>
</body>

Including KaTeX CSS is necessary in the way you are convenient with, either link the stylesheet from a third party CDN into the local HTML <head> tag or import it into a currently linked CSS stylesheets to enable styles for KaTeX globally as follows,

Or, you could clone or download the entire repository source of KaTeX and self load the fonts/styles/scripts locally, but if you prefer loading from third-party CDN with faster load speed when deployed to save your server resources, the following CDN links might be your choice, you can always switch to other platforms based on your need.

html
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16/dist/katex.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16/dist/katex.min.css" />
html
<link rel="stylesheet" href="https://gcore.jsdelivr.net/npm/katex@0.16/dist/katex.min.css" />
<link rel="stylesheet" href="https://gcore.jsdelivr.net/npm/katex@0.16/dist/katex.min.css" />
html
<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/katex@0.16/dist/katex.min.css" />
<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/katex@0.16/dist/katex.min.css" />
html
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.0/katex.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.0/katex.min.css" />
html
<link rel="stylesheet" href="https://unpkg.com/katex@0.16.0/dist/katex.min.css" />
<link rel="stylesheet" href="https://unpkg.com/katex@0.16.0/dist/katex.min.css" />
scss
// ... your other styles
@import 'https://cdnjs.toshiki.dev/ajax/libs/KaTeX/0.16.0/katex.min.css';
// ... your other styles
@import 'https://cdnjs.toshiki.dev/ajax/libs/KaTeX/0.16.0/katex.min.css';

If you are using the default markdown-it parser, I personally recommend that you use the GitHub markdown CSS (github-markdown-css) for styling your HTML output with a similar style replica of GitHub's markdown styling to your familiarity.

html
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@5.2.0/github-markdown.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@5.2.0/github-markdown.min.css" />

This forked project maintained by Anda Toshiki comes with the update of KaTeX components with higher style version support (this documentation uses KaTeX version 16.0, without hassels), later versions may works, but no guarantees are given by the developers, if you are not obsessed with the latest released version, 16.0 may fits your need for loading KaTeX on a personal blog site or small educational sites; yet it should work fully functionally.

Warning

Since this project is a fork of the original markdown-it-katex project that hasn't been receiving any active updates of its code source for years, the latest katex style version supported is somewhere around ver. 0.9.0 which clearly is outdated and results in broken styles with overflowing and other potential bug presents.

2: Usage

RTo render equations, you need to include the markdown-it-katex plugin in the markdown-it components in your JavaScript or TypeScript file as follows,

js
var md = require('markdown-it')(),
    mk = require('andatoshiki/markdown-it-katex')

md.use(mk)

// double backslash is required for javascript strings, but not html input
var result = md.render('# Math Rulez! \n  $\\sqrt{3x-1}+(1+x)^2$')
var md = require('markdown-it')(),
    mk = require('andatoshiki/markdown-it-katex')

md.use(mk)

// double backslash is required for javascript strings, but not html input
var result = md.render('# Math Rulez! \n  $\\sqrt{3x-1}+(1+x)^2$')
ts
import * as mk from 'markdown-it-katex'
import * as MarkdownIt from '@andatoshiki/markdown-it'

const md = new MarkdownIt()
md.use(mk)

// double backslash is not required for TypeScript strings or template literals
const result = md.render('# Math Rulez! \n  $\\sqrt{3x-1}+(1+x)^2$')
import * as mk from 'markdown-it-katex'
import * as MarkdownIt from '@andatoshiki/markdown-it'

const md = new MarkdownIt()
md.use(mk)

// double backslash is not required for TypeScript strings or template literals
const result = md.render('# Math Rulez! \n  $\\sqrt{3x-1}+(1+x)^2$')

3: Configuration

The following list of variable are the customizable components of markdown-it-katex, adjust to your needs,

  • katex: You can change KaTeX version by passing the instance.
  • blockClass: Class added to KaTeX block.
  • Apply any other KaTeX options if needed as a regard to the docs
js
md.use(mk, { blockClass: 'math-block', errorColor: ' #cc0000' })
md.use(mk, { blockClass: 'math-block', errorColor: ' #cc0000' })

4: Examples

4.1: Inline math

To render your LaTeX equations inline, enclose them with a single dollar sign $ on each side of the equation as follows,

tex
$\sqrt{3x-1}+(1+x)^2$
$\sqrt{3x-1}+(1+x)^2$

rendered output equation as follows, 3x1+(1+x)2\sqrt{3x-1}+(1+x)^2.

4.2: Blocked math

To render blocks, use double dollar sign ($$). This mode utilizes larger symbols and centers the result as a block displayed as a <div> block in HTML output, as follows,

tex
$$
\frac {\partial^r} {\partial \omega^r} \left(\frac {y^{\omega}} {\omega}\right)
= \left(\frac {y^{\omega}} {\omega}\right) \left\{(\log y)^r + \sum_{i=1}^r \frac {(-1)^ Ir \cdots (r-i+1) (\log y)^{ri}} {\omega^i} \right\}
$$
$$
\frac {\partial^r} {\partial \omega^r} \left(\frac {y^{\omega}} {\omega}\right)
= \left(\frac {y^{\omega}} {\omega}\right) \left\{(\log y)^r + \sum_{i=1}^r \frac {(-1)^ Ir \cdots (r-i+1) (\log y)^{ri}} {\omega^i} \right\}
$$

the above block equation renders the LaTeX equation as a block with output as follows,

rωr(yωω)=(yωω){(logy)r+i=1r(1)Ir(ri+1)(logy)riωi}\frac {\partial^r} {\partial \omega^r} \left(\frac {y^{\omega}} {\omega}\right) = \left(\frac {y^{\omega}} {\omega}\right) \left\{(\log y)^r + \sum_{i=1}^r \frac {(-1)^ Ir \cdots (r-i+1) (\log y)^{ri}} {\omega^i} \right\}

5: Syntax

Math parsing in markdown is designed to comply with the "latex-in-markdown" conventions set by Pandoc,

Anything between two $ characters will be treated as TeX math. The opening $ must have a non-space character immediately to its right, while the closing $ must have a non-space character immediately to its left, and must not be followed immediately by a digit. Thus, $20,000 and $30,000 won’t parse as math. If for some reason you need to enclose text in literal $ characters, backslash-escape them and they won’t be treated as math delimiters.

  • Pandoc. “Pandoc - Pandoc User’s Guide.” Pandoc.org, pandoc.org/MANUAL.html#math. Accessed 2 Mar. 2023.

6: Supported math syntax

KaTeX is a popular, open-source math typesetting library that is based on TeX and LaTeX. It is designed to be easy to use, and to provide high-quality mathematical typesetting for web applications, refer to the following pages of the document for the full list of function support in KaTeX.

Note

Due to the large number of equations rendered on the next following pages, it might takes time to entirely load the webpage, please be patient if the webpage seems to not respond; or it could be a result of slow network connection to correctly render all the equation that causes broken formulas, refresh the page to proceed.

]]>
@andatoshiki/markdown-it-katex

Add graceful KaTeX\KaTeX rendering to your Markdown like a charm with markdown-it plugin.

1: Installation

Before you start using this plugin, make sure you have already installed the default markdown-it parser; if not, please run the following command or refer to the official markdown-it documentation.

sh
$ npm install markdown-it --save
$ npm install markdown-it --save

First install package with your preferred package manager (npm, yarn, pnpm), or include javascript before the closing </body> for markdown-it-katex's core utils to be loaded for the static page.

sh
$ npm install -D @andatoshiki/markdown-it-katex
$ npm install -D @andatoshiki/markdown-it-katex
sh
$ yarn add --dev @andatoshiki/markdown-it-katex
$ yarn add --dev @andatoshiki/markdown-it-katex
sh
$ pnpm add -D @andatoshiki/markdown-it-katex
$ pnpm add -D @andatoshiki/markdown-it-katex
html
<!-- your other body contents ... -->
    <script src="https://unpkg.com/@andatoshiki/markdown-it-katex@0.0.3/markdown-it-katex.min.js"></script>
</body>
<!-- your other body contents ... -->
    <script src="https://unpkg.com/@andatoshiki/markdown-it-katex@0.0.3/markdown-it-katex.min.js"></script>
</body>

Including KaTeX CSS is necessary in the way you are convenient with, either link the stylesheet from a third party CDN into the local HTML <head> tag or import it into a currently linked CSS stylesheets to enable styles for KaTeX globally as follows,

Or, you could clone or download the entire repository source of KaTeX and self load the fonts/styles/scripts locally, but if you prefer loading from third-party CDN with faster load speed when deployed to save your server resources, the following CDN links might be your choice, you can always switch to other platforms based on your need.

html
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16/dist/katex.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16/dist/katex.min.css" />
html
<link rel="stylesheet" href="https://gcore.jsdelivr.net/npm/katex@0.16/dist/katex.min.css" />
<link rel="stylesheet" href="https://gcore.jsdelivr.net/npm/katex@0.16/dist/katex.min.css" />
html
<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/katex@0.16/dist/katex.min.css" />
<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/katex@0.16/dist/katex.min.css" />
html
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.0/katex.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.0/katex.min.css" />
html
<link rel="stylesheet" href="https://unpkg.com/katex@0.16.0/dist/katex.min.css" />
<link rel="stylesheet" href="https://unpkg.com/katex@0.16.0/dist/katex.min.css" />
scss
// ... your other styles
@import 'https://cdnjs.toshiki.dev/ajax/libs/KaTeX/0.16.0/katex.min.css';
// ... your other styles
@import 'https://cdnjs.toshiki.dev/ajax/libs/KaTeX/0.16.0/katex.min.css';

If you are using the default markdown-it parser, I personally recommend that you use the GitHub markdown CSS (github-markdown-css) for styling your HTML output with a similar style replica of GitHub's markdown styling to your familiarity.

html
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@5.2.0/github-markdown.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@5.2.0/github-markdown.min.css" />

This forked project maintained by Anda Toshiki comes with the update of KaTeX components with higher style version support (this documentation uses KaTeX version 16.0, without hassels), later versions may works, but no guarantees are given by the developers, if you are not obsessed with the latest released version, 16.0 may fits your need for loading KaTeX on a personal blog site or small educational sites; yet it should work fully functionally.

Warning

Since this project is a fork of the original markdown-it-katex project that hasn't been receiving any active updates of its code source for years, the latest katex style version supported is somewhere around ver. 0.9.0 which clearly is outdated and results in broken styles with overflowing and other potential bug presents.

2: Usage

RTo render equations, you need to include the markdown-it-katex plugin in the markdown-it components in your JavaScript or TypeScript file as follows,

js
var md = require('markdown-it')(),
    mk = require('andatoshiki/markdown-it-katex')

md.use(mk)

// double backslash is required for javascript strings, but not html input
var result = md.render('# Math Rulez! \n  $\\sqrt{3x-1}+(1+x)^2$')
var md = require('markdown-it')(),
    mk = require('andatoshiki/markdown-it-katex')

md.use(mk)

// double backslash is required for javascript strings, but not html input
var result = md.render('# Math Rulez! \n  $\\sqrt{3x-1}+(1+x)^2$')
ts
import * as mk from 'markdown-it-katex'
import * as MarkdownIt from '@andatoshiki/markdown-it'

const md = new MarkdownIt()
md.use(mk)

// double backslash is not required for TypeScript strings or template literals
const result = md.render('# Math Rulez! \n  $\\sqrt{3x-1}+(1+x)^2$')
import * as mk from 'markdown-it-katex'
import * as MarkdownIt from '@andatoshiki/markdown-it'

const md = new MarkdownIt()
md.use(mk)

// double backslash is not required for TypeScript strings or template literals
const result = md.render('# Math Rulez! \n  $\\sqrt{3x-1}+(1+x)^2$')

3: Configuration

The following list of variable are the customizable components of markdown-it-katex, adjust to your needs,

  • katex: You can change KaTeX version by passing the instance.
  • blockClass: Class added to KaTeX block.
  • Apply any other KaTeX options if needed as a regard to the docs
js
md.use(mk, { blockClass: 'math-block', errorColor: ' #cc0000' })
md.use(mk, { blockClass: 'math-block', errorColor: ' #cc0000' })

4: Examples

4.1: Inline math

To render your LaTeX equations inline, enclose them with a single dollar sign $ on each side of the equation as follows,

tex
$\sqrt{3x-1}+(1+x)^2$
$\sqrt{3x-1}+(1+x)^2$

rendered output equation as follows, 3x1+(1+x)2\sqrt{3x-1}+(1+x)^2.

4.2: Blocked math

To render blocks, use double dollar sign ($$). This mode utilizes larger symbols and centers the result as a block displayed as a <div> block in HTML output, as follows,

tex
$$
\frac {\partial^r} {\partial \omega^r} \left(\frac {y^{\omega}} {\omega}\right)
= \left(\frac {y^{\omega}} {\omega}\right) \left\{(\log y)^r + \sum_{i=1}^r \frac {(-1)^ Ir \cdots (r-i+1) (\log y)^{ri}} {\omega^i} \right\}
$$
$$
\frac {\partial^r} {\partial \omega^r} \left(\frac {y^{\omega}} {\omega}\right)
= \left(\frac {y^{\omega}} {\omega}\right) \left\{(\log y)^r + \sum_{i=1}^r \frac {(-1)^ Ir \cdots (r-i+1) (\log y)^{ri}} {\omega^i} \right\}
$$

the above block equation renders the LaTeX equation as a block with output as follows,

rωr(yωω)=(yωω){(logy)r+i=1r(1)Ir(ri+1)(logy)riωi}\frac {\partial^r} {\partial \omega^r} \left(\frac {y^{\omega}} {\omega}\right) = \left(\frac {y^{\omega}} {\omega}\right) \left\{(\log y)^r + \sum_{i=1}^r \frac {(-1)^ Ir \cdots (r-i+1) (\log y)^{ri}} {\omega^i} \right\}

5: Syntax

Math parsing in markdown is designed to comply with the "latex-in-markdown" conventions set by Pandoc,

Anything between two $ characters will be treated as TeX math. The opening $ must have a non-space character immediately to its right, while the closing $ must have a non-space character immediately to its left, and must not be followed immediately by a digit. Thus, $20,000 and $30,000 won’t parse as math. If for some reason you need to enclose text in literal $ characters, backslash-escape them and they won’t be treated as math delimiters.

  • Pandoc. “Pandoc - Pandoc User’s Guide.” Pandoc.org, pandoc.org/MANUAL.html#math. Accessed 2 Mar. 2023.

6: Supported math syntax

KaTeX is a popular, open-source math typesetting library that is based on TeX and LaTeX. It is designed to be easy to use, and to provide high-quality mathematical typesetting for web applications, refer to the following pages of the document for the full list of function support in KaTeX.

Note

Due to the large number of equations rendered on the next following pages, it might takes time to entirely load the webpage, please be patient if the webpage seems to not respond; or it could be a result of slow network connection to correctly render all the equation that causes broken formulas, refresh the page to proceed.

]]>
<![CDATA[KaTeX: Supported functions]]> https://note.toshiki.dev/application/markdown-it-katex/support-function https://note.toshiki.dev/application/markdown-it-katex/support-function Thu, 01 Jul 2021 00:00:00 GMT KaTeX: Supported function

note

This is an direct shameful copy of the documentation pulled from KaTeX documentation, I do not own any of the content below on behalf of this part of the documentation, the table might be outdated as versions migrates, please also refer to KaTeX's official documentation.

This following is a list of TeX functions supported by KaTeX. It is sorted into logical groups.

There is a similar Support Table on the next page, sorted alphabetically in am more intuitive way with the lists both supported and un-supported functions, viewing both tables are suggested comprehensibly and interchangeably is highly suggested.

1: Accents

aa' a' a~\tilde{a} \tilde{a} g˚\mathring{g} \mathring{g}
aa'' a'' ac~\widetilde{ac} \widetilde{ac} AB\overgroup{AB} \overgroup{AB}
aa^{\prime} a^{\prime} AB~\utilde{AB} \utilde{AB} AB\undergroup{AB} \undergroup{AB}
aˊ\acute{a} \acute{a} F\vec{F} \vec{F} AB\Overrightarrow{AB} \Overrightarrow{AB}
yˉ\bar{y} \bar{y} AB\overleftarrow{AB} \overleftarrow{AB} AB\overrightarrow{AB} \overrightarrow{AB}
a˘\breve{a} \breve{a} AB\underleftarrow{AB} \underleftarrow{AB} AB\underrightarrow{AB} \underrightarrow{AB}
aˇ\check{a} \check{a} ac\overleftharpoon{ac} \overleftharpoon{ac} ac\overrightharpoon{ac} \overrightharpoon{ac}
a˙\dot{a} \dot{a} AB\overleftrightarrow{AB} \overleftrightarrow{AB} AB\overbrace{AB} \overbrace{AB}
a¨\ddot{a} \ddot{a} AB\underleftrightarrow{AB} \underleftrightarrow{AB} AB\underbrace{AB} \underbrace{AB}
aˋ\grave{a} \grave{a} AB\overline{AB} \overline{AB} ABundefined\overlinesegment{AB} \overlinesegment{AB}
θ^\hat{\theta} \hat{\theta} AB\underline{AB} \underline{AB} ABundefined\underlinesegment{AB} \underlinesegment{AB}
ac^\widehat{ac} \widehat{ac} acˇ\widecheck{ac} \widecheck{ac}

Accent functions inside \text{…}

aˊ\text{\'{a}} \'{a} a˜\text{\~{a}} \~{a} a˙\text{\.{a}} \.{a} a˝\text{\H{a}} \H{a}
aˋ\text{\`{a}} \`{a} aˉ\text{\={a}} \={a} a¨\text{\"{a}} \"{a} aˇ\text{\v{a}} \v{a}
aˆ\text{\^{a}} \^{a} a˘\text{\u{a}} \u{a} a˚\text{\r{a}} \r{a}

See also letters.

2: Delimiters

( )(~) ( ) ( )\lparen~\rparen \lparen
    ~~~~\rparen
 ⌈~⌉ ⌈ ⌉  \lceil~\rceil \lceil
     ~~~~~\rceil
\uparrow \uparrow
[ ][~] [ ] [ ]\lbrack~\rbrack \lbrack
    ~~~~\rbrack
 ⌊~⌋ ⌊ ⌋  \lfloor~\rfloor \lfloor
     ~~~~~\rfloor
\downarrow \downarrow
{}\{ \} \{ \} {}\lbrace \rbrace \lbrace
    ~~~~\rbrace
⎰⎱ ⎰⎱ \lmoustache \rmoustache \lmoustache
    ~~~~\rmoustache
\updownarrow \updownarrow
 ⟨~⟩ ⟨ ⟩  \langle~\rangle \langle
    ~~~~\rangle
 ⟮~⟯ ⟮ ⟯  \lgroup~\rgroup \lgroup
     ~~~~~\rgroup
\Uparrow \Uparrow
\vert | \vert \vert ┌ ┐ ┌ ┐ \ulcorner \urcorner \ulcorner
    ~~~~\urcorner
\Downarrow \Downarrow
\Vert \| \Vert \Vert └ ┘ └ ┘ \llcorner \lrcorner \llcorner
    ~~~~\lrcorner
\Updownarrow \Updownarrow
 \lvert~\rvert \lvert
    ~~~~\rvert
 \lVert~\rVert \lVert
     ~~~~~\rVert
\left. \right. \\backslash \backslash
 \lang~\rang \lang
    ~~~~\rang
< >\lt~\gt \lt \gt

Delimiter Sizing

(AB)\left(\LARGE{AB}\right) \left(\LARGE{AB}\right)

(((((( \big( \Big( \bigg( \Bigg( ( \big( \Big( \bigg( \Bigg(

\left \big \bigl \bigm \bigr
\middle \Big \Bigl \Bigm \Bigr
\right \bigg \biggl \biggm \biggr
\Bigg \Biggl \Biggm \Biggr

3: Environments

abcd\begin{matrix} a & b \\ c & d \end{matrix} \begin{matrix}
   a & b \\
   c & d
\end{matrix}
abcd\begin{array}{cc}a & b\\c & d\end{array} \begin{array}{cc}
   a & b \\
   c & d
\end{array}
(abcd)\begin{pmatrix} a & b \\ c & d \end{pmatrix} \begin{pmatrix}
   a & b \\
   c & d
\end{pmatrix}
[abcd]\begin{bmatrix} a & b \\ c & d \end{bmatrix} \begin{bmatrix}
   a & b \\
   c & d
\end{bmatrix}
abcd\begin{vmatrix} a & b \\ c & d \end{vmatrix} \begin{vmatrix}
   a & b \\
   c & d
\end{vmatrix}
abcd\begin{Vmatrix} a & b \\ c & d \end{Vmatrix} \begin{Vmatrix}
   a & b \\
   c & d
\end{Vmatrix}
{abcd}\begin{Bmatrix} a & b \\ c & d \end{Bmatrix} \begin{Bmatrix}
   a & b \\
   c & d
\end{Bmatrix}
abcdefghi\def\arraystretch{1.5}\begin{array}{c:c:c} a & b & c \\ \hline d & e & f \\ \hdashline g & h & i \end{array} \def\arraystretch{1.5}
   \begin{array}{c:c:c}
   a & b & c \\ \hline
   d & e & f \\
   \hdashline
   g & h & i
\end{array}
a=b+cd+e=f\begin{aligned} a&=b+c \\ d+e&=f \end{aligned} \begin{aligned}
   a&=b+c \\
   d+e&=f
\end{aligned}
10x+3y=23x+13y=4\begin{alignedat}{2}10&x+&3&y=2\\3&x+&13&y=4\end{alignedat} \begin{alignedat}{2}
   10&x+ &3&y = 2 \\
    3&x+&13&y = 4
\end{alignedat}
a=be=b+c\begin{gathered} a=b \\ e=b+c \end{gathered} \begin{gathered}
   a=b \\
   e=b+c
\end{gathered}
x={aif bcif dx = \begin{cases} a &\text{if } b \\ c &\text{if } d \end{cases} x = \begin{cases}
   a &\text{if } b \\
   c &\text{if } d
\end{cases}

KaTeX also supports darray and dcases.

Acceptable line separators include: \\, \cr, \\[distance], and \cr[distance]. Distance can be written with any of the KaTeX units.

The {array} environment supports | and : vertical separators.

The {array} environment does not yet support \cline or \multicolumn.

4: HTML

\href\href{https://katex.org/}{\KaTeX} \href{https://katex.org/}{\KaTeX}
\url\url{https://katex.org/} \url{https://katex.org/}

5: Letters and Unicode

Greek Letters

Direct Input: ABΓΔEZHΘIKΛMNΞOΠPΣTΥΦXΨΩΑ Β Γ Δ Ε Ζ Η Θ Ι \allowbreak Κ Λ Μ Ν Ξ Ο Π Ρ Σ Τ Υ Φ Χ Ψ Ω αβγδϵζηθικλμνξoπρστυϕχψωεϑϖϱςφ\allowbreak α β γ δ ϵ ζ η θ ι κ λ μ ν ξ o π \allowbreak ρ σ τ υ ϕ χ ψ ω ε ϑ ϖ ϱ ς φ

A\Alpha \Alpha B\Beta \Beta Γ\Gamma \Gamma Δ\Delta \Delta
E\Epsilon \Epsilon Z\Zeta \Zeta H\Eta \Eta Θ\Theta \Theta
I\Iota \Iota K\Kappa \Kappa Λ\Lambda \Lambda M\Mu \Mu
N\Nu \Nu Ξ\Xi \Xi O\Omicron \Omicron Π\Pi \Pi
Σ\Sigma \Sigma T\Tau \Tau Υ\Upsilon \Upsilon Φ\Phi \Phi
X\Chi \Chi Ψ\Psi \Psi Ω\Omega \Omega
Γ\varGamma \varGamma Δ\varDelta \varDelta Θ\varTheta \varTheta Λ\varLambda \varLambda
Ξ\varXi \varXi Π\varPi \varPi Σ\varSigma \varSigma Υ\varUpsilon \varUpsilon
Φ\varPhi \varPhi Ψ\varPsi \varPsi Ω\varOmega \varOmega
α\alpha \alpha β\beta \beta γ\gamma \gamma δ\delta \delta
ϵ\epsilon \epsilon ζ\zeta \zeta η\eta \eta θ\theta \theta
ι\iota \iota κ\kappa \kappa λ\lambda \lambda μ\mu \mu
ν\nu \nu ξ\xi \xi ο\omicron \omicron π\pi \pi
ρ\rho \rho σ\sigma \sigma τ\tau \tau υ\upsilon \upsilon
ϕ\phi \phi χ\chi \chi ψ\psi \psi ω\omega \omega
ε\varepsilon \varepsilon ϰ\varkappa \varkappa ϑ\vartheta \vartheta ϑ\thetasym \thetasym
ϖ\varpi \varpi ϱ\varrho \varrho ς\varsigma \varsigma φ\varphi \varphi

| ϝ\digamma \digamma

Other Letters

ı\imath \imath \nabla \nabla \Im \Im R\Reals \Reals Œ\text{\OE} \text{\OE}
ȷ\jmath \jmath \partial \partial \image \image \wp \wp ø\text{\o} \text{\o}
\aleph \aleph \Game \Game k\Bbbk \Bbbk \weierp \weierp Ø\text{\O} \text{\O}
\alef \alef \Finv \Finv N\N \N Z\Z \Z ß\text{\ss} \text{\ss}
\alefsym \alefsym C\cnums \cnums N\natnums \natnums a˚\text{\aa} \text{\aa} ı\text{\i} \text{\i}
\beth \beth C\Complex \Complex R\R \R A˚\text{\AA} \text{\AA} ȷ\text{\j} \text{\j}
\gimel \gimel \ell \ell \Re \Re æ\text{\ae} \text{\ae}
\daleth \daleth \hbar \hbar \real \real Æ\text{\AE} \text{\AE}
ð\eth \eth \hslash \hslash R\reals \reals œ\text{\oe} \text{\oe}

Direct Input: ð∂ ∇ ℑ Ⅎ ℵ ℶ ℷ ℸ ⅁ ℏ ð ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝÞßàáâãäåçèéêëìíîïðñòóôöùúûüýþÿ

Unicode Mathematical Alphanumeric Symbols

Item Range Item Range
Bold 𝐀-𝐙 𝐚-𝐳 𝟎-𝟗\text{𝐀-𝐙 𝐚-𝐳 𝟎-𝟗} Double-struck 𝔸-Z 𝕜\text{𝔸-}ℤ\ 𝕜
Italic 𝐴-𝑍 𝑎-𝑧\text{𝐴-𝑍 𝑎-𝑧} Sans serif 𝖠-𝖹 𝖺-𝗓 𝟢-𝟫\text{𝖠-𝖹 𝖺-𝗓 𝟢-𝟫}
Bold Italic 𝑨-𝒁 𝒂-𝒛\text{𝑨-𝒁 𝒂-𝒛} Sans serif bold 𝗔-𝗭 𝗮-𝘇 𝟬-𝟵\text{𝗔-𝗭 𝗮-𝘇 𝟬-𝟵}
Script 𝒜-𝒵\text{𝒜-𝒵} Sans serif italic 𝘈-𝘡 𝘢-𝘻\text{𝘈-𝘡 𝘢-𝘻}
Fractur 𝔄-Z 𝔞-𝔷\text{𝔄-}ℨ\text{ 𝔞-𝔷} Monospace 𝙰-𝚉 𝚊-𝚣 𝟶-𝟿\text{𝙰-𝚉 𝚊-𝚣 𝟶-𝟿}

Unicode

The letters listed above will render in any KaTeX rendering mode.

If the KaTeX rendering mode is set to strict: false or strict:"warn" (default), then KaTeX will accept all Unicode letters. The letters not listed above will be rendered from system fonts, not KaTeX-supplied fonts, so their typography may clash. They may also cause small vertical alignment issues. KaTeX has detailed metrics for glyphs in Latin, Greek, and Cyrillic, but other glyphs are treated as if they are each as tall as the letter M.

For Persian composite characters, a user-supplied plug-in is under development.

6: Layout

6.1: Annotation

5\cancel{5} \cancel{5} a+b+cnote\overbrace{a+b+c}^{\text{note}} \overbrace{a+b+c}^{\text{note}}
5\bcancel{5} \bcancel{5} a+b+cnote\underbrace{a+b+c}_{\text{note}} \underbrace{a+b+c}_{\text{note}}
ABC\xcancel{ABC} \xcancel{ABC} \not = \not =
abc\sout{abc} \sout{abc} π=cd\boxed{\pi=\frac c d} \boxed{\pi=\frac c d}

\tag{hi} x+y^{2x}

x+y2x(hi)\tag{hi} x+y^{2x}

\tag*{hi} x+y^{2x}

x+y2xhi\tag*{hi} x+y^{2x}

6.2: Line Breaks

KaTeX 0.10.0+ will insert automatic line breaks in inline math after relations or binary operators such as “=” or “+”. These can be suppressed by \nobreak or by placing math inside a pair of braces, as in {F=ma}. \allowbreak will allow automatic line breaks at locations other than relations or operators.

Hard line breaks are \\ and \newline.

In display math, KaTeX does not insert automatic line breaks. It ignores display math hard line breaks when rendering option strict: true.

6.3: Vertical Layout

xnx_n x_n =!\stackrel{!}{=} \stackrel{!}{=} aba \atop b a \atop b
exe^x e^x =!\overset{!}{=} \overset{!}{=} abca\raisebox{0.25em}{b}c a\raisebox{0.25em}{b}c
$_u^o $ _u^o =!\underset{!}{=} \underset{!}{=}

The second argument of \raisebox can contain math if it is nested within $…$ delimiters, as in \raisebox{0.25em}{$\frac a b$}

6.4: Overlap and Spacing

=/{=}\mathllap{/\,} {=}\mathllap{/\,} (x2)\left(x^{\smash{2}}\right) \left(x^{\smash{2}}\right)
/=\mathrlap{\,/}{=} \mathrlap{\,/}{=} y\sqrt{\smash[b]{y}} \sqrt{\smash[b]{y}}

1ijnxij\displaystyle\sum_{\mathclap{1\le i\le j\le n}} x_{ij} \sum_{\mathclap{1\le i\le j\le n}} x_{ij}

KaTeX also supports \llap, \rlap, and \clap, but they will take only text, not math, as arguments.

Spacing

Function Produces Function Produces
\, ³∕₁₈ em space \kern{distance} space, width = distance
\thinspace ³∕₁₈ em space \mkern{distance} space, width = distance
\: ⁴∕₁₈ em space \mskip{distance} space, width = distance
\medspace ⁴∕₁₈ em space \hskip{distance} space, width = distance
\; ⁵∕₁₈ em space \hspace{distance} space, width = distance
\thickspace ⁵∕₁₈ em space \hspace*{distance} space, width = distance
\enspace ½ em space \phantom{content} space the width and height of content
\quad 1 em space \hphantom{content} space the width of content
\qquad 2 em space \vphantom{content} a strut the height of content
~ non-breaking space \! – ³∕₁₈ em space
\<space> space \negthinspace – ³∕₁₈ em space
\nobreakspace non-breaking space \negmedspace – ⁴∕₁₈ em space
\space space \negthickspace – ⁵∕₁₈ em space

Notes:

distance will accept any of the KaTeX units.

\kern, \mkern, \mskip, and \hspace accept unbraced distances, as in: \kern1em.

\mkern and \mskip will not work in text mode and both will write a console warning for any unit except mu.

7: Logic and Set Theory

\forall \forall \complement \complement \therefore \therefore \emptyset \emptyset
\exists \exists \subset \subset \because \because \empty \empty
\exist \exist \supset \supset \mapsto \mapsto \varnothing \varnothing
\nexists \nexists \mid \mid \to \to     \implies \implies
\in \in \land \land \gets \gets     \impliedby \impliedby
\isin \isin \lor \lor \leftrightarrow \leftrightarrow     \iff \iff
\notin \notin \ni \ni \notni \notni ¬\neg \neg or \lnot

Direct Input: ¬∀ ∴ ∁ ∵ ∃ ∣ ∈ ∉ ∋ ⊂ ⊃ ∧ ∨ ↦ → ← ↔ ¬ ℂ ℍ ℕ ℙ ℚ ℝ

8: Macros

x2+x2\def\foo{x^2} \foo + \foo \def\foo{x^2} \foo + \foo
y2+y2\gdef\bar#1{#1^2} \bar{y} + \bar{y} \gdef\bar#1{#1^2} \bar{y} + \bar{y}
\global\def\macroname#1#2…{definition}
\newcommand\macroname[numargs]{definition}
\renewcommand\macroname[numargs]{definition}
\providecommand\macroname[numargs]{definition}

Macros can also be defined in the KaTeX rendering options.

Macros accept up to nine arguments: #1, #2, etc.

\gdef and \global\def macros will persist between math expressions.

Available functions include:

\char \mathchoice \TextOrMath \@ifstar \@ifnextchar \@firstoftwo \@secondoftwo \relax

@ is a valid character for commands, as if \makeatletter were in effect.

9: Operators

9.1: Big Operators

\sum \sum \prod \prod \bigotimes \bigotimes \bigvee \bigvee
\int \int \coprod \coprod \bigoplus \bigoplus \bigwedge \bigwedge
\iint \iint \intop \intop \bigodot \bigodot \bigcap \bigcap
\iiint \iiint \smallint \smallint \biguplus \biguplus \bigcup \bigcup
\oint \oint \oiint \oiint \oiiint \oiiint \bigsqcup \bigsqcup

Direct Input: ∫ ∬ ∭ ∮ ∏ ∐ ∑ ⋀ ⋁ ⋂ ⋃ ⨀ ⨁ ⨂ ⨄ ⨆

9.2: Binary Operators

++ + \cdot \cdot \gtrdot \gtrdot x(moda)x \pmod a x \pmod a
- - \cdotp \cdotp \intercal \intercal x(a)x \pod a x \pod a
// / \centerdot \centerdot \land \land \rhd \rhd
* * \circ \circ \leftthreetimes \leftthreetimes \rightthreetimes \rightthreetimes
⨿\amalg \amalg \circledast \circledast .\ldotp \ldotp \rtimes \rtimes
&\And \And \circledcirc \circledcirc \lor \lor \setminus \setminus
\ast \ast \circleddash \circleddash \lessdot \lessdot \smallsetminus \smallsetminus
\barwedge \barwedge \Cup \Cup \lhd \lhd \sqcap \sqcap
\bigcirc \bigcirc \cup \cup \ltimes \ltimes \sqcup \sqcup
mod\bmod \bmod \curlyvee \curlyvee xmodax \mod a x\mod a ×\times \times
\boxdot \boxdot \curlywedge \curlywedge \mp \mp \unlhd \unlhd
\boxminus \boxminus ÷\div \div \odot \odot \unrhd \unrhd
\boxplus \boxplus \divideontimes \divideontimes \ominus \ominus \uplus \uplus
\boxtimes \boxtimes \dotplus \dotplus \oplus \oplus \vee \vee
\bullet \bullet \doublebarwedge \doublebarwedge \otimes \otimes \veebar \veebar
\Cap \Cap \doublecap \doublecap \oslash \oslash \wedge \wedge
\cap \cap \doublecup \doublecup ±\pm \pm or \plusmn \wr \wr

Direct Input: +/±×÷+ - / * ⋅ ± × ÷ ∓ ∔ ∧ ∨ ∩ ∪ ≀ ⊎ ⊓ ⊔ ⊕ ⊖ ⊗ ⊘ ⊙ ⊚ ⊛ ⊝

9.3: Fractions and Binomials

ab\frac{a}{b} \frac{a}{b} ab\tfrac{a}{b} \tfrac{a}{b} (aa+1]\genfrac ( ] {2pt}{1}a{a+1} \genfrac ( ] {2pt}{1}a{a+1}
ab{a \over b} {a \over b} ab\dfrac{a}{b} \dfrac{a}{b} ab+1{a \above{2pt} b+1} {a \above{2pt} b+1}
a/ba/b a/b a1+1b\cfrac{a}{1 + \cfrac{1}{b}} \cfrac{a}{1 + \cfrac{1}{b}}
(nk)\binom{n}{k} \binom{n}{k} (nk)\dbinom{n}{k} \dbinom{n}{k} {nk}{n\brace k} {n\brace k}
(nk){n \choose k} {n \choose k} (nk)\tbinom{n}{k} \tbinom{n}{k} [nk]{n\brack k} {n\brack k}

9.4: Math Operators

arcsin\arcsin \arcsin cotg\cotg \cotg ln\ln \ln det\det \det
arccos\arccos \arccos coth\coth \coth log\log \log gcd\gcd \gcd
arctan\arctan \arctan csc\csc \csc sec\sec \sec inf\inf \inf
arctg\arctg \arctg ctg\ctg \ctg sin\sin \sin lim\lim \lim
arcctg\arcctg \arcctg cth\cth \cth sinh\sinh \sinh lim inf\liminf \liminf
arg\arg \arg deg\deg \deg sh\sh \sh lim sup\limsup \limsup
ch\ch \ch dim\dim \dim tan\tan \tan max\max \max
cos\cos \cos exp\exp \exp tanh\tanh \tanh min\min \min
cosec\cosec \cosec hom\hom \hom tg\tg \tg Pr\Pr \Pr
cosh\cosh \cosh ker\ker \ker th\th \th sup\sup \sup
cot\cot \cot lg\lg \lg f\operatorname{f} \operatorname{f}

Functions on the right column of this table can take \limits.

9.5: \sqrt

x\sqrt{x} \sqrt{x}

x3\sqrt[3]{x} \sqrt[3]{x}

10: Relations

=!\stackrel{!}{=} \stackrel{!}{=}

== = \eqcirc \eqcirc \lesseqgtr \lesseqgtr \sqsupset \sqsupset
<< < \eqcolon \eqcolon \lesseqqgtr \lesseqqgtr \sqsupseteq \sqsupseteq
>> > \Eqcolon \Eqcolon \lessgtr \lessgtr \Subset \Subset
:: : \eqqcolon \eqqcolon \lesssim \lesssim \subset \subset or \sub
\approx \approx =\Eqqcolon \Eqqcolon \ll \ll \subseteq \subseteq or \sube
\approxeq \approxeq \eqsim \eqsim \lll \lll \subseteqq \subseteqq
\asymp \asymp \eqslantgtr \eqslantgtr \llless \llless \succ \succ
\backepsilon \backepsilon \eqslantless \eqslantless <\lt \lt \succapprox \succapprox
\backsim \backsim \equiv \equiv \mid \mid \succcurlyeq \succcurlyeq
\backsimeq \backsimeq \fallingdotseq \fallingdotseq \models \models \succeq \succeq
\between \between \frown \frown \multimap \multimap \succsim \succsim
\bowtie \bowtie \ge \ge \owns \owns \Supset \Supset
\bumpeq \bumpeq \geq \geq \parallel \parallel \supset \supset
\Bumpeq \Bumpeq \geqq \geqq \perp \perp \supseteq \supseteq or \supe
\circeq \circeq \geqslant \geqslant \pitchfork \pitchfork \supseteqq \supseteqq
:\colonapprox \colonapprox \gg \gg \prec \prec \thickapprox \thickapprox
\Colonapprox \Colonapprox \ggg \ggg \precapprox \precapprox \thicksim \thicksim
:\coloneq \coloneq \gggtr \gggtr \preccurlyeq \preccurlyeq \trianglelefteq \trianglelefteq
\Coloneq \Coloneq >\gt \gt \preceq \preceq \triangleq \triangleq
\coloneqq \coloneqq \gtrapprox \gtrapprox \precsim \precsim \trianglerighteq \trianglerighteq
=\Coloneqq \Coloneqq \gtreqless \gtreqless \propto \propto \varpropto \varpropto
:\colonsim \colonsim \gtreqqless \gtreqqless \risingdotseq \risingdotseq \vartriangle \vartriangle
\Colonsim \Colonsim \gtrless \gtrless \shortmid \shortmid \vartriangleleft \vartriangleleft
\cong \cong \gtrsim \gtrsim \shortparallel \shortparallel \vartriangleright \vartriangleright
\curlyeqprec \curlyeqprec \in \in or \isin \sim \sim :\vcentcolon \vcentcolon
\curlyeqsucc \curlyeqsucc \Join \Join \simeq \simeq \vdash \vdash
\dashv \dashv \le \le \smallfrown \smallfrown \vDash \vDash
\dblcolon \dblcolon \leq \leq \smallsmile \smallsmile \Vdash \Vdash
\doteq \doteq \leqq \leqq \smile \smile \Vvdash \Vvdash
\Doteq \Doteq \leqslant \leqslant \sqsubset \sqsubset
\doteqdot \doteqdot \lessapprox \lessapprox \sqsubseteq \sqsubseteq

Direct Input: =<>:= < > : ∈ ∋ ∝ ∼ ∽ ≂ ≃ ≅ ≈ ≊ ≍ ≎ ≏ ≐ ≑ ≒ ≓ ≖ ≗ ≜ ≡ ≤ ≥ ≦ ≧ ≫ ≬ ≳ ≷ ≺ ≻ ≼ ≽ ≾ ≿ ⊂ ⊃ ⊆ ⊇ ⊏ ⊐ ⊑ ⊒ ⊢ ⊣ ⊩ ⊪ ⊸ ⋈ ⋍ ⋐ ⋑ ⋔ ⋙ ⋛ ⋞ ⋟ ⌢ ⌣ ⩾ ⪆ ⪌ ⪕ ⪖ ⪯ ⪰ ⪷ ⪸ ⫅ ⫆ ≲ ⩽ ⪅ ≶ ⋚ ⪋ ⟂ ⊨ ≔ ≕ ⩴

10.1: Negated Relations

\not = \not =

\gnapprox \gnapprox \ngeqslant \ngeqslant \nsubseteq \nsubseteq \precneqq \precneqq
\gneq \gneq \ngtr \ngtr \nsubseteqq \nsubseteqq \precnsim \precnsim
\gneqq \gneqq \nleq \nleq \nsucc \nsucc \subsetneq \subsetneq
\gnsim \gnsim \nleqq \nleqq \nsucceq \nsucceq \subsetneqq \subsetneqq
\gvertneqq \gvertneqq \nleqslant \nleqslant \nsupseteq \nsupseteq \succnapprox \succnapprox
\lnapprox \lnapprox \nless \nless \nsupseteqq \nsupseteqq \succneqq \succneqq
\lneq \lneq \nmid \nmid \ntriangleleft \ntriangleleft \succnsim \succnsim
\lneqq \lneqq \notin \notin \ntrianglelefteq \ntrianglelefteq \supsetneq \supsetneq
\lnsim \lnsim \notni \notni \ntriangleright \ntriangleright \supsetneqq \supsetneqq
\lvertneqq \lvertneqq \nparallel \nparallel \ntrianglerighteq \ntrianglerighteq \varsubsetneq \varsubsetneq
\ncong \ncong \nprec \nprec \nvdash \nvdash \varsubsetneqq \varsubsetneqq
\ne \ne \npreceq \npreceq \nvDash \nvDash \varsupsetneq \varsupsetneq
\neq \neq \nshortmid \nshortmid \nVDash \nVDash \varsupsetneqq \varsupsetneqq
\ngeq \ngeq \nshortparallel \nshortparallel \nVdash \nVdash
\ngeqq \ngeqq \nsim \nsim \precnapprox \precnapprox

Direct Input:

∉ ∌ ∤ ∦ ≁ ≆ ≠ ≨ ≩ ≮ ≯ ≰ ≱ ⊀ ⊁ ⊈ ⊉ ⊊ ⊋ ⊬ ⊭ ⊮ ⊯ ⋠ ⋡ ⋦ ⋧ ⋨ ⋩ ⋬ ⋭ ⪇ ⪈ ⪉ ⪊ ⪵ ⪶ ⪹ ⪺ ⫋ ⫌

10.2: Arrows

\circlearrowleft \circlearrowleft \leftharpoonup \leftharpoonup \rArr \rArr
\circlearrowright \circlearrowright \leftleftarrows \leftleftarrows \rarr \rarr
\curvearrowleft \curvearrowleft \leftrightarrow \leftrightarrow \restriction \restriction
\curvearrowright \curvearrowright \Leftrightarrow \Leftrightarrow \rightarrow \rightarrow
\Darr \Darr \leftrightarrows \leftrightarrows \Rightarrow \Rightarrow
\dArr \dArr \leftrightharpoons \leftrightharpoons \rightarrowtail \rightarrowtail
\darr \darr \leftrightsquigarrow \leftrightsquigarrow \rightharpoondown \rightharpoondown
\dashleftarrow \dashleftarrow \Lleftarrow \Lleftarrow \rightharpoonup \rightharpoonup
\dashrightarrow \dashrightarrow \longleftarrow \longleftarrow \rightleftarrows \rightleftarrows
\downarrow \downarrow \Longleftarrow \Longleftarrow \rightleftharpoons \rightleftharpoons
\Downarrow \Downarrow \longleftrightarrow \longleftrightarrow \rightrightarrows \rightrightarrows
\downdownarrows \downdownarrows \Longleftrightarrow \Longleftrightarrow \rightsquigarrow \rightsquigarrow
\downharpoonleft \downharpoonleft \longmapsto \longmapsto \Rrightarrow \Rrightarrow
\downharpoonright \downharpoonright \longrightarrow \longrightarrow \Rsh \Rsh
\gets \gets \Longrightarrow \Longrightarrow \searrow \searrow
\Harr \Harr \looparrowleft \looparrowleft \swarrow \swarrow
\hArr \hArr \looparrowright \looparrowright \to \to
\harr \harr \Lrarr \Lrarr \twoheadleftarrow \twoheadleftarrow
\hookleftarrow \hookleftarrow \lrArr \lrArr \twoheadrightarrow \twoheadrightarrow
\hookrightarrow \hookrightarrow \lrarr \lrarr \Uarr \Uarr
    \iff \iff \Lsh \Lsh \uArr \uArr
    \impliedby \impliedby \mapsto \mapsto \uarr \uarr
    \implies \implies \nearrow \nearrow \uparrow \uparrow
\Larr \Larr \nleftarrow \nleftarrow \Uparrow \Uparrow
\lArr \lArr \nLeftarrow \nLeftarrow \updownarrow \updownarrow
\larr \larr \nleftrightarrow \nleftrightarrow \Updownarrow \Updownarrow
\leadsto \leadsto \nLeftrightarrow \nLeftrightarrow \upharpoonleft \upharpoonleft
\leftarrow \leftarrow \nrightarrow \nrightarrow \upharpoonright \upharpoonright
\Leftarrow \Leftarrow \nRightarrow \nRightarrow \upuparrows \upuparrows
\leftarrowtail \leftarrowtail \nwarrow \nwarrow
\leftharpoondown \leftharpoondown \Rarr \Rarr

Direct Input: ← ↑ → ↓ ↔ ↕ ↖ ↗ ↘ ↙ ↚ ↛ ↞ ↠ ↢ ↣ ↦ ↩ ↪ ↫ ↬ ↭ ↮ ↰ ↱↶ ↷ ↺ ↻ ↼ ↽ ↾ ↾ ↿ ⇀ ⇁ ⇂ ⇃ ⇄ ⇆ ⇇ ⇈ ⇉ ⇊ ⇋ ⇌⇍ ⇎ ⇏ ⇐ ⇑ ⇒ ⇓ ⇔ ⇕ ⇚ ⇛ ⇝ ⇠ ⇢ ⟵ ⟶ ⟷ ⟸ ⟹ ⟺ ⟼

Extensible Arrows

abc\xleftarrow{abc} \xleftarrow{abc} underover\xrightarrow[under]{over} \xrightarrow[under]{over}
abc\xLeftarrow{abc} \xLeftarrow{abc} abc\xRightarrow{abc} \xRightarrow{abc}
abc\xleftrightarrow{abc} \xleftrightarrow{abc} abc\xLeftrightarrow{abc} \xLeftrightarrow{abc}
abc\xhookleftarrow{abc} \xhookleftarrow{abc} abc\xhookrightarrow{abc} \xhookrightarrow{abc}
abc\xtwoheadleftarrow{abc} \xtwoheadleftarrow{abc} abc\xtwoheadrightarrow{abc} \xtwoheadrightarrow{abc}
abc\xleftharpoonup{abc} \xleftharpoonup{abc} abc\xrightharpoonup{abc} \xrightharpoonup{abc}
abc\xleftharpoondown{abc} \xleftharpoondown{abc} abc\xrightharpoondown{abc} \xrightharpoondown{abc}
abc\xleftrightharpoons{abc} \xleftrightharpoons{abc} abc\xrightleftharpoons{abc} \xrightleftharpoons{abc}
abc\xtofrom{abc} \xtofrom{abc} abc\xmapsto{abc} \xmapsto{abc}

|=abc\xlongequal{abc} \xlongequal{abc}

Extensible arrows all can take an optional argument in the same manner, as \xrightarrow[under]{over}.

11: Style, Color, Size, and Font

Class Assignment

  • \mathbin \mathclose \mathinner \mathop

  • \mathopen \mathord \mathpunct \mathrel

Color

F=ma\color{blue} F=ma \color{blue} F=ma

Note that KaTeX \color acts like a switch. This aligns with LaTeX and differs from MathJax. Other KaTeX color functions expect the content to be a function argument:

  • F=ma\textcolor{blue}{F=ma} \textcolor{blue}{F=ma}
  • F=ma\textcolor{#228B22}{F=ma} \textcolor{#228B22}{F=ma}
  • A\colorbox{aqua}{A} \colorbox{aqua}{A}
  • A\fcolorbox{red}{aqua}{A} \fcolorbox{red}{aqua}{A}

For color definition, KaTeX color functions will accept the standard HTML predefined color names. They will also accept an RGB argument in CSS hexa­decimal style. The "#" is optional before a six-digit specification.

Font

Ab0\mathrm{Ab0} \mathrm{Ab0} Ab0\mathbf{Ab0} \mathbf{Ab0} Ab\mathit{Ab} \mathit{Ab}
Ab0\mathnormal{Ab0} \mathnormal{Ab0} Ab0\textbf{Ab0} \textbf{Ab0} Ab\textit{Ab} \textit{Ab}
Ab0\textrm{Ab0} \textrm{Ab0} Ab0\bf Ab0 \bf Ab0 Ab\it Ab \it Ab
Ab0\rm Ab0 \rm Ab0 Ab0\bold{Ab0} \bold{Ab0} AB\Bbb{AB} \Bbb{AB}
Ab0\textnormal{Ab0} \textnormal{Ab0} Ab\boldsymbol{Ab} \boldsymbol{Ab} AB\mathbb{AB} \mathbb{AB}
Ab0\text{Ab0} \text{Ab0} Ab\bm{Ab} \bm{Ab} Ab0\frak{Ab0} \frak{Ab0}
Ab0\mathsf{Ab0} \mathsf{Ab0} Ab0\mathtt{Ab0} \mathtt{Ab0} Ab0\mathfrak{Ab0} \mathfrak{Ab0}
Ab0\textsf{Ab0} \textsf{Ab0} Ab0\texttt{Ab0} \texttt{Ab0} AB0\mathcal{AB0} \mathcal{AB0}
Ab0\sf Ab0 \sf Ab0 Ab0\tt Ab0 \tt Ab0 AB\mathscr{AB} \mathscr{AB}

One can stack font family, font weight, and font shape by using the \textXX versions of the font functions. So \textsf{\textbf{H}} will produce H\textsf{\textbf{H}}. The other versions do not stack, e.g., \mathsf{\mathbf{H}} will produce H\mathsf{\mathbf{H}}.

In cases where KaTeX fonts do not have a bold glyph, \pmb can simulate one. For example, \pmb{\mu} renders as : μ\pmb{\mu}

Size

AB\Huge AB \Huge AB AB\normalsize AB \normalsize AB
AB\huge AB \huge AB AB\small AB \small AB
AB\LARGE AB \LARGE AB AB\footnotesize AB \footnotesize AB
AB\Large AB \Large AB AB\scriptsize AB \scriptsize AB
AB\large AB \large AB AB\tiny AB \tiny AB

Style

|i=1n\displaystyle\sum_{i=1}^n \displaystyle\sum_{i=1}^n |i=1n\textstyle\sum_{i=1}^n \textstyle\sum_{i=1}^n |x\scriptstyle x \scriptstyle x         (The size of a first sub/superscript) |x\scriptscriptstyle x \scriptscriptstyle x (The size of subsequent sub/superscripts) |limx\lim\limits_x \lim\limits_x |limx\lim\nolimits_x \lim\nolimits_x |x^2\verb!x^2! \verb!x^2!

\text{…} will accept nested $…$ fragments and render them in math mode.

12: Symbols and Punctuation

% comment \dots \dots KaTeX\KaTeX \KaTeX
%\% \% \cdots \cdots LaTeX\LaTeX \LaTeX
#\# \# \ddots \ddots TeX\TeX \TeX
&\& \& \ldots \ldots \nabla \nabla
_\_ \_ \vdots \vdots \infty \infty
_\text{\textunderscore} \text{\textunderscore} \dotsb \dotsb \infin \infin
\text{--} \text{--} \dotsc \dotsc \checkmark \checkmark
\text{\textendash} \text{\textendash}  ⁣\dotsi \dotsi \dag \dag
\text{---} \text{---} \dotsm \dotsm \dagger \dagger
\text{\textemdash} \text{\textemdash} \dotso \dotso \text{\textdagger} \text{\textdagger}
~\text{\textasciitilde} \text{\textasciitilde} \sdot \sdot \ddag \ddag
` ` \mathellipsis \mathellipsis \ddagger \ddagger
\text{\textquoteleft} text{\textquoteleft} \text{\textellipsis} \text{\textellipsis} \text{\textdaggerdbl} \text{\textdaggerdbl}
\lq \lq \Box \Box \Dagger \Dagger
\text{\textquoteright} \text{\textquoteright} \square \square \angle \angle
\rq \rq \blacksquare \blacksquare \measuredangle \measuredangle
\text{\textquotedblleft} \text{\textquotedblleft} \triangle \triangle \sphericalangle \sphericalangle
"" " \triangledown \triangledown \top \top
\text{\textquotedblright} \text{\textquotedblright} \triangleleft \triangleleft \bot \bot
 ⁣:\colon \colon \triangleright \triangleright $\$ \$
\backprime \backprime \bigtriangledown \bigtriangledown $\text{\textdollar} \text{\textdollar}
\prime \prime \bigtriangleup \bigtriangleup £\pounds \pounds
<\text{\textless} \text{\textless} \blacktriangle \blacktriangle £\mathsterling \mathsterling
>\text{\textgreater} \text{\textgreater} \blacktriangledown \blacktriangledown £\text{\textsterling} \text{\textsterling}
|\text{\textbar} \text{\textbar} \blacktriangleleft \blacktriangleleft ¥\yen \yen
\text{\textbardbl} \text{\textbardbl} \blacktriangleright \blacktriangleright \surd \surd
{\text{\textbraceleft} \text{\textbraceleft} \diamond \diamond °\degree \degree
}\text{\textbraceright} \text{\textbraceright} \Diamond \Diamond °\text{\textdegree} \text{\textdegree}
\text{\P} \text{\P} \lozenge \lozenge \mho \mho
§\text{\S} \text{\S} \blacklozenge \blacklozenge \diagdown \diagdown
§\text{\sect} \text{\sect} \star \star \diagup \diagup
©\copyright \copyright \bigstar \bigstar \flat \flat
®\circledR \circledR \clubsuit \clubsuit \natural \natural
®\text{\textregistered} \text{\textregistered} \clubs \clubs \sharp \sharp
\circledS \circledS \diamondsuit \diamondsuit \heartsuit \heartsuit
a\text{\textcircled a} \text{\textcircled a} \diamonds \diamonds \hearts \hearts
\maltese \maltese \spadesuit \spadesuit \spades \spades

Direct Input: £¥!£ ¥ ∇ ∞ · ∠ ∡ ∢ ♠ ♡ ♢ ♣ ♭ ♮ ♯ ✓ … ⋮ ⋯ ⋱ !

13: Units

In KaTeX, units are proportioned as they are in TeX. KaTeX units are different than CSS units.

KaTeX Unit Value KaTeX Unit Value
em CSS em bp 1/72​ inch × F × G
ex CSS ex pc 12 KaTeX pt
mu 1/18 CSS em dd 1238/1157​ KaTeX pt
pt 1/72.27 inch × F × G cc 14856/1157 KaTeX pt
mm 1 mm × F × G nd 685/642 KaTeX pt
cm 1 cm × F × G nc 1370/107​ KaTeX pt
in 1 inch × F × G sp 1/65536 KaTeX pt

where:

  • F = (font size of surrounding HTML text)/(10 pt)

  • G = 1.21 by default, because KaTeX font-size is normally 1.21 × the surrounding font size. This value can be overridden by the CSS of an HTML page.

The effect of style and size:

Unit textstyle scriptscript huge
em or ex \rule{1em}{1em} \scriptscriptstyle\rule{1em}{1em} \huge\rule{1em}{1em}
mu \rule{18mu}{18mu} \scriptscriptstyle\rule{18mu}{18mu} \huge\rule{18mu}{18mu}
others \rule{10pt}{10pt} \scriptscriptstyle\rule{10pt}{10pt} \huge\rule{10pt}{10pt}
]]>
KaTeX: Supported function

note

This is an direct shameful copy of the documentation pulled from KaTeX documentation, I do not own any of the content below on behalf of this part of the documentation, the table might be outdated as versions migrates, please also refer to KaTeX's official documentation.

This following is a list of TeX functions supported by KaTeX. It is sorted into logical groups.

There is a similar Support Table on the next page, sorted alphabetically in am more intuitive way with the lists both supported and un-supported functions, viewing both tables are suggested comprehensibly and interchangeably is highly suggested.

1: Accents

aa' a' a~\tilde{a} \tilde{a} g˚\mathring{g} \mathring{g}
aa'' a'' ac~\widetilde{ac} \widetilde{ac} AB\overgroup{AB} \overgroup{AB}
aa^{\prime} a^{\prime} AB~\utilde{AB} \utilde{AB} AB\undergroup{AB} \undergroup{AB}
aˊ\acute{a} \acute{a} F\vec{F} \vec{F} AB\Overrightarrow{AB} \Overrightarrow{AB}
yˉ\bar{y} \bar{y} AB\overleftarrow{AB} \overleftarrow{AB} AB\overrightarrow{AB} \overrightarrow{AB}
a˘\breve{a} \breve{a} AB\underleftarrow{AB} \underleftarrow{AB} AB\underrightarrow{AB} \underrightarrow{AB}
aˇ\check{a} \check{a} ac\overleftharpoon{ac} \overleftharpoon{ac} ac\overrightharpoon{ac} \overrightharpoon{ac}
a˙\dot{a} \dot{a} AB\overleftrightarrow{AB} \overleftrightarrow{AB} AB\overbrace{AB} \overbrace{AB}
a¨\ddot{a} \ddot{a} AB\underleftrightarrow{AB} \underleftrightarrow{AB} AB\underbrace{AB} \underbrace{AB}
aˋ\grave{a} \grave{a} AB\overline{AB} \overline{AB} ABundefined\overlinesegment{AB} \overlinesegment{AB}
θ^\hat{\theta} \hat{\theta} AB\underline{AB} \underline{AB} ABundefined\underlinesegment{AB} \underlinesegment{AB}
ac^\widehat{ac} \widehat{ac} acˇ\widecheck{ac} \widecheck{ac}

Accent functions inside \text{…}

aˊ\text{\'{a}} \'{a} a˜\text{\~{a}} \~{a} a˙\text{\.{a}} \.{a} a˝\text{\H{a}} \H{a}
aˋ\text{\`{a}} \`{a} aˉ\text{\={a}} \={a} a¨\text{\"{a}} \"{a} aˇ\text{\v{a}} \v{a}
aˆ\text{\^{a}} \^{a} a˘\text{\u{a}} \u{a} a˚\text{\r{a}} \r{a}

See also letters.

2: Delimiters

( )(~) ( ) ( )\lparen~\rparen \lparen
    ~~~~\rparen
 ⌈~⌉ ⌈ ⌉  \lceil~\rceil \lceil
     ~~~~~\rceil
\uparrow \uparrow
[ ][~] [ ] [ ]\lbrack~\rbrack \lbrack
    ~~~~\rbrack
 ⌊~⌋ ⌊ ⌋  \lfloor~\rfloor \lfloor
     ~~~~~\rfloor
\downarrow \downarrow
{}\{ \} \{ \} {}\lbrace \rbrace \lbrace
    ~~~~\rbrace
⎰⎱ ⎰⎱ \lmoustache \rmoustache \lmoustache
    ~~~~\rmoustache
\updownarrow \updownarrow
 ⟨~⟩ ⟨ ⟩  \langle~\rangle \langle
    ~~~~\rangle
 ⟮~⟯ ⟮ ⟯  \lgroup~\rgroup \lgroup
     ~~~~~\rgroup
\Uparrow \Uparrow
\vert | \vert \vert ┌ ┐ ┌ ┐ \ulcorner \urcorner \ulcorner
    ~~~~\urcorner
\Downarrow \Downarrow
\Vert \| \Vert \Vert └ ┘ └ ┘ \llcorner \lrcorner \llcorner
    ~~~~\lrcorner
\Updownarrow \Updownarrow
 \lvert~\rvert \lvert
    ~~~~\rvert
 \lVert~\rVert \lVert
     ~~~~~\rVert
\left. \right. \\backslash \backslash
 \lang~\rang \lang
    ~~~~\rang
< >\lt~\gt \lt \gt

Delimiter Sizing

(AB)\left(\LARGE{AB}\right) \left(\LARGE{AB}\right)

(((((( \big( \Big( \bigg( \Bigg( ( \big( \Big( \bigg( \Bigg(

\left \big \bigl \bigm \bigr
\middle \Big \Bigl \Bigm \Bigr
\right \bigg \biggl \biggm \biggr
\Bigg \Biggl \Biggm \Biggr

3: Environments

abcd\begin{matrix} a & b \\ c & d \end{matrix} \begin{matrix}
   a & b \\
   c & d
\end{matrix}
abcd\begin{array}{cc}a & b\\c & d\end{array} \begin{array}{cc}
   a & b \\
   c & d
\end{array}
(abcd)\begin{pmatrix} a & b \\ c & d \end{pmatrix} \begin{pmatrix}
   a & b \\
   c & d
\end{pmatrix}
[abcd]\begin{bmatrix} a & b \\ c & d \end{bmatrix} \begin{bmatrix}
   a & b \\
   c & d
\end{bmatrix}
abcd\begin{vmatrix} a & b \\ c & d \end{vmatrix} \begin{vmatrix}
   a & b \\
   c & d
\end{vmatrix}
abcd\begin{Vmatrix} a & b \\ c & d \end{Vmatrix} \begin{Vmatrix}
   a & b \\
   c & d
\end{Vmatrix}
{abcd}\begin{Bmatrix} a & b \\ c & d \end{Bmatrix} \begin{Bmatrix}
   a & b \\
   c & d
\end{Bmatrix}
abcdefghi\def\arraystretch{1.5}\begin{array}{c:c:c} a & b & c \\ \hline d & e & f \\ \hdashline g & h & i \end{array} \def\arraystretch{1.5}
   \begin{array}{c:c:c}
   a & b & c \\ \hline
   d & e & f \\
   \hdashline
   g & h & i
\end{array}
a=b+cd+e=f\begin{aligned} a&=b+c \\ d+e&=f \end{aligned} \begin{aligned}
   a&=b+c \\
   d+e&=f
\end{aligned}
10x+3y=23x+13y=4\begin{alignedat}{2}10&x+&3&y=2\\3&x+&13&y=4\end{alignedat} \begin{alignedat}{2}
   10&x+ &3&y = 2 \\
    3&x+&13&y = 4
\end{alignedat}
a=be=b+c\begin{gathered} a=b \\ e=b+c \end{gathered} \begin{gathered}
   a=b \\
   e=b+c
\end{gathered}
x={aif bcif dx = \begin{cases} a &\text{if } b \\ c &\text{if } d \end{cases} x = \begin{cases}
   a &\text{if } b \\
   c &\text{if } d
\end{cases}

KaTeX also supports darray and dcases.

Acceptable line separators include: \\, \cr, \\[distance], and \cr[distance]. Distance can be written with any of the KaTeX units.

The {array} environment supports | and : vertical separators.

The {array} environment does not yet support \cline or \multicolumn.

4: HTML

\href\href{https://katex.org/}{\KaTeX} \href{https://katex.org/}{\KaTeX}
\url\url{https://katex.org/} \url{https://katex.org/}

5: Letters and Unicode

Greek Letters

Direct Input: ABΓΔEZHΘIKΛMNΞOΠPΣTΥΦXΨΩΑ Β Γ Δ Ε Ζ Η Θ Ι \allowbreak Κ Λ Μ Ν Ξ Ο Π Ρ Σ Τ Υ Φ Χ Ψ Ω αβγδϵζηθικλμνξoπρστυϕχψωεϑϖϱςφ\allowbreak α β γ δ ϵ ζ η θ ι κ λ μ ν ξ o π \allowbreak ρ σ τ υ ϕ χ ψ ω ε ϑ ϖ ϱ ς φ

A\Alpha \Alpha B\Beta \Beta Γ\Gamma \Gamma Δ\Delta \Delta
E\Epsilon \Epsilon Z\Zeta \Zeta H\Eta \Eta Θ\Theta \Theta
I\Iota \Iota K\Kappa \Kappa Λ\Lambda \Lambda M\Mu \Mu
N\Nu \Nu Ξ\Xi \Xi O\Omicron \Omicron Π\Pi \Pi
Σ\Sigma \Sigma T\Tau \Tau Υ\Upsilon \Upsilon Φ\Phi \Phi
X\Chi \Chi Ψ\Psi \Psi Ω\Omega \Omega
Γ\varGamma \varGamma Δ\varDelta \varDelta Θ\varTheta \varTheta Λ\varLambda \varLambda
Ξ\varXi \varXi Π\varPi \varPi Σ\varSigma \varSigma Υ\varUpsilon \varUpsilon
Φ\varPhi \varPhi Ψ\varPsi \varPsi Ω\varOmega \varOmega
α\alpha \alpha β\beta \beta γ\gamma \gamma δ\delta \delta
ϵ\epsilon \epsilon ζ\zeta \zeta η\eta \eta θ\theta \theta
ι\iota \iota κ\kappa \kappa λ\lambda \lambda μ\mu \mu
ν\nu \nu ξ\xi \xi ο\omicron \omicron π\pi \pi
ρ\rho \rho σ\sigma \sigma τ\tau \tau υ\upsilon \upsilon
ϕ\phi \phi χ\chi \chi ψ\psi \psi ω\omega \omega
ε\varepsilon \varepsilon ϰ\varkappa \varkappa ϑ\vartheta \vartheta ϑ\thetasym \thetasym
ϖ\varpi \varpi ϱ\varrho \varrho ς\varsigma \varsigma φ\varphi \varphi

| ϝ\digamma \digamma

Other Letters

ı\imath \imath \nabla \nabla \Im \Im R\Reals \Reals Œ\text{\OE} \text{\OE}
ȷ\jmath \jmath \partial \partial \image \image \wp \wp ø\text{\o} \text{\o}
\aleph \aleph \Game \Game k\Bbbk \Bbbk \weierp \weierp Ø\text{\O} \text{\O}
\alef \alef \Finv \Finv N\N \N Z\Z \Z ß\text{\ss} \text{\ss}
\alefsym \alefsym C\cnums \cnums N\natnums \natnums a˚\text{\aa} \text{\aa} ı\text{\i} \text{\i}
\beth \beth C\Complex \Complex R\R \R A˚\text{\AA} \text{\AA} ȷ\text{\j} \text{\j}
\gimel \gimel \ell \ell \Re \Re æ\text{\ae} \text{\ae}
\daleth \daleth \hbar \hbar \real \real Æ\text{\AE} \text{\AE}
ð\eth \eth \hslash \hslash R\reals \reals œ\text{\oe} \text{\oe}

Direct Input: ð∂ ∇ ℑ Ⅎ ℵ ℶ ℷ ℸ ⅁ ℏ ð ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝÞßàáâãäåçèéêëìíîïðñòóôöùúûüýþÿ

Unicode Mathematical Alphanumeric Symbols

Item Range Item Range
Bold 𝐀-𝐙 𝐚-𝐳 𝟎-𝟗\text{𝐀-𝐙 𝐚-𝐳 𝟎-𝟗} Double-struck 𝔸-Z 𝕜\text{𝔸-}ℤ\ 𝕜
Italic 𝐴-𝑍 𝑎-𝑧\text{𝐴-𝑍 𝑎-𝑧} Sans serif 𝖠-𝖹 𝖺-𝗓 𝟢-𝟫\text{𝖠-𝖹 𝖺-𝗓 𝟢-𝟫}
Bold Italic 𝑨-𝒁 𝒂-𝒛\text{𝑨-𝒁 𝒂-𝒛} Sans serif bold 𝗔-𝗭 𝗮-𝘇 𝟬-𝟵\text{𝗔-𝗭 𝗮-𝘇 𝟬-𝟵}
Script 𝒜-𝒵\text{𝒜-𝒵} Sans serif italic 𝘈-𝘡 𝘢-𝘻\text{𝘈-𝘡 𝘢-𝘻}
Fractur 𝔄-Z 𝔞-𝔷\text{𝔄-}ℨ\text{ 𝔞-𝔷} Monospace 𝙰-𝚉 𝚊-𝚣 𝟶-𝟿\text{𝙰-𝚉 𝚊-𝚣 𝟶-𝟿}

Unicode

The letters listed above will render in any KaTeX rendering mode.

If the KaTeX rendering mode is set to strict: false or strict:"warn" (default), then KaTeX will accept all Unicode letters. The letters not listed above will be rendered from system fonts, not KaTeX-supplied fonts, so their typography may clash. They may also cause small vertical alignment issues. KaTeX has detailed metrics for glyphs in Latin, Greek, and Cyrillic, but other glyphs are treated as if they are each as tall as the letter M.

For Persian composite characters, a user-supplied plug-in is under development.

6: Layout

6.1: Annotation

5\cancel{5} \cancel{5} a+b+cnote\overbrace{a+b+c}^{\text{note}} \overbrace{a+b+c}^{\text{note}}
5\bcancel{5} \bcancel{5} a+b+cnote\underbrace{a+b+c}_{\text{note}} \underbrace{a+b+c}_{\text{note}}
ABC\xcancel{ABC} \xcancel{ABC} \not = \not =
abc\sout{abc} \sout{abc} π=cd\boxed{\pi=\frac c d} \boxed{\pi=\frac c d}

\tag{hi} x+y^{2x}

x+y2x(hi)\tag{hi} x+y^{2x}

\tag*{hi} x+y^{2x}

x+y2xhi\tag*{hi} x+y^{2x}

6.2: Line Breaks

KaTeX 0.10.0+ will insert automatic line breaks in inline math after relations or binary operators such as “=” or “+”. These can be suppressed by \nobreak or by placing math inside a pair of braces, as in {F=ma}. \allowbreak will allow automatic line breaks at locations other than relations or operators.

Hard line breaks are \\ and \newline.

In display math, KaTeX does not insert automatic line breaks. It ignores display math hard line breaks when rendering option strict: true.

6.3: Vertical Layout

xnx_n x_n =!\stackrel{!}{=} \stackrel{!}{=} aba \atop b a \atop b
exe^x e^x =!\overset{!}{=} \overset{!}{=} abca\raisebox{0.25em}{b}c a\raisebox{0.25em}{b}c
$_u^o $ _u^o =!\underset{!}{=} \underset{!}{=}

The second argument of \raisebox can contain math if it is nested within $…$ delimiters, as in \raisebox{0.25em}{$\frac a b$}

6.4: Overlap and Spacing

=/{=}\mathllap{/\,} {=}\mathllap{/\,} (x2)\left(x^{\smash{2}}\right) \left(x^{\smash{2}}\right)
/=\mathrlap{\,/}{=} \mathrlap{\,/}{=} y\sqrt{\smash[b]{y}} \sqrt{\smash[b]{y}}

1ijnxij\displaystyle\sum_{\mathclap{1\le i\le j\le n}} x_{ij} \sum_{\mathclap{1\le i\le j\le n}} x_{ij}

KaTeX also supports \llap, \rlap, and \clap, but they will take only text, not math, as arguments.

Spacing

Function Produces Function Produces
\, ³∕₁₈ em space \kern{distance} space, width = distance
\thinspace ³∕₁₈ em space \mkern{distance} space, width = distance
\: ⁴∕₁₈ em space \mskip{distance} space, width = distance
\medspace ⁴∕₁₈ em space \hskip{distance} space, width = distance
\; ⁵∕₁₈ em space \hspace{distance} space, width = distance
\thickspace ⁵∕₁₈ em space \hspace*{distance} space, width = distance
\enspace ½ em space \phantom{content} space the width and height of content
\quad 1 em space \hphantom{content} space the width of content
\qquad 2 em space \vphantom{content} a strut the height of content
~ non-breaking space \! – ³∕₁₈ em space
\<space> space \negthinspace – ³∕₁₈ em space
\nobreakspace non-breaking space \negmedspace – ⁴∕₁₈ em space
\space space \negthickspace – ⁵∕₁₈ em space

Notes:

distance will accept any of the KaTeX units.

\kern, \mkern, \mskip, and \hspace accept unbraced distances, as in: \kern1em.

\mkern and \mskip will not work in text mode and both will write a console warning for any unit except mu.

7: Logic and Set Theory

\forall \forall \complement \complement \therefore \therefore \emptyset \emptyset
\exists \exists \subset \subset \because \because \empty \empty
\exist \exist \supset \supset \mapsto \mapsto \varnothing \varnothing
\nexists \nexists \mid \mid \to \to     \implies \implies
\in \in \land \land \gets \gets     \impliedby \impliedby
\isin \isin \lor \lor \leftrightarrow \leftrightarrow     \iff \iff
\notin \notin \ni \ni \notni \notni ¬\neg \neg or \lnot

Direct Input: ¬∀ ∴ ∁ ∵ ∃ ∣ ∈ ∉ ∋ ⊂ ⊃ ∧ ∨ ↦ → ← ↔ ¬ ℂ ℍ ℕ ℙ ℚ ℝ

8: Macros

x2+x2\def\foo{x^2} \foo + \foo \def\foo{x^2} \foo + \foo
y2+y2\gdef\bar#1{#1^2} \bar{y} + \bar{y} \gdef\bar#1{#1^2} \bar{y} + \bar{y}
\global\def\macroname#1#2…{definition}
\newcommand\macroname[numargs]{definition}
\renewcommand\macroname[numargs]{definition}
\providecommand\macroname[numargs]{definition}

Macros can also be defined in the KaTeX rendering options.

Macros accept up to nine arguments: #1, #2, etc.

\gdef and \global\def macros will persist between math expressions.

Available functions include:

\char \mathchoice \TextOrMath \@ifstar \@ifnextchar \@firstoftwo \@secondoftwo \relax

@ is a valid character for commands, as if \makeatletter were in effect.

9: Operators

9.1: Big Operators

\sum \sum \prod \prod \bigotimes \bigotimes \bigvee \bigvee
\int \int \coprod \coprod \bigoplus \bigoplus \bigwedge \bigwedge
\iint \iint \intop \intop \bigodot \bigodot \bigcap \bigcap
\iiint \iiint \smallint \smallint \biguplus \biguplus \bigcup \bigcup
\oint \oint \oiint \oiint \oiiint \oiiint \bigsqcup \bigsqcup

Direct Input: ∫ ∬ ∭ ∮ ∏ ∐ ∑ ⋀ ⋁ ⋂ ⋃ ⨀ ⨁ ⨂ ⨄ ⨆

9.2: Binary Operators

++ + \cdot \cdot \gtrdot \gtrdot x(moda)x \pmod a x \pmod a
- - \cdotp \cdotp \intercal \intercal x(a)x \pod a x \pod a
// / \centerdot \centerdot \land \land \rhd \rhd
* * \circ \circ \leftthreetimes \leftthreetimes \rightthreetimes \rightthreetimes
⨿\amalg \amalg \circledast \circledast .\ldotp \ldotp \rtimes \rtimes
&\And \And \circledcirc \circledcirc \lor \lor \setminus \setminus
\ast \ast \circleddash \circleddash \lessdot \lessdot \smallsetminus \smallsetminus
\barwedge \barwedge \Cup \Cup \lhd \lhd \sqcap \sqcap
\bigcirc \bigcirc \cup \cup \ltimes \ltimes \sqcup \sqcup
mod\bmod \bmod \curlyvee \curlyvee xmodax \mod a x\mod a ×\times \times
\boxdot \boxdot \curlywedge \curlywedge \mp \mp \unlhd \unlhd
\boxminus \boxminus ÷\div \div \odot \odot \unrhd \unrhd
\boxplus \boxplus \divideontimes \divideontimes \ominus \ominus \uplus \uplus
\boxtimes \boxtimes \dotplus \dotplus \oplus \oplus \vee \vee
\bullet \bullet \doublebarwedge \doublebarwedge \otimes \otimes \veebar \veebar
\Cap \Cap \doublecap \doublecap \oslash \oslash \wedge \wedge
\cap \cap \doublecup \doublecup ±\pm \pm or \plusmn \wr \wr

Direct Input: +/±×÷+ - / * ⋅ ± × ÷ ∓ ∔ ∧ ∨ ∩ ∪ ≀ ⊎ ⊓ ⊔ ⊕ ⊖ ⊗ ⊘ ⊙ ⊚ ⊛ ⊝

9.3: Fractions and Binomials

ab\frac{a}{b} \frac{a}{b} ab\tfrac{a}{b} \tfrac{a}{b} (aa+1]\genfrac ( ] {2pt}{1}a{a+1} \genfrac ( ] {2pt}{1}a{a+1}
ab{a \over b} {a \over b} ab\dfrac{a}{b} \dfrac{a}{b} ab+1{a \above{2pt} b+1} {a \above{2pt} b+1}
a/ba/b a/b a1+1b\cfrac{a}{1 + \cfrac{1}{b}} \cfrac{a}{1 + \cfrac{1}{b}}
(nk)\binom{n}{k} \binom{n}{k} (nk)\dbinom{n}{k} \dbinom{n}{k} {nk}{n\brace k} {n\brace k}
(nk){n \choose k} {n \choose k} (nk)\tbinom{n}{k} \tbinom{n}{k} [nk]{n\brack k} {n\brack k}

9.4: Math Operators

arcsin\arcsin \arcsin cotg\cotg \cotg ln\ln \ln det\det \det
arccos\arccos \arccos coth\coth \coth log\log \log gcd\gcd \gcd
arctan\arctan \arctan csc\csc \csc sec\sec \sec inf\inf \inf
arctg\arctg \arctg ctg\ctg \ctg sin\sin \sin lim\lim \lim
arcctg\arcctg \arcctg cth\cth \cth sinh\sinh \sinh lim inf\liminf \liminf
arg\arg \arg deg\deg \deg sh\sh \sh lim sup\limsup \limsup
ch\ch \ch dim\dim \dim tan\tan \tan max\max \max
cos\cos \cos exp\exp \exp tanh\tanh \tanh min\min \min
cosec\cosec \cosec hom\hom \hom tg\tg \tg Pr\Pr \Pr
cosh\cosh \cosh ker\ker \ker th\th \th sup\sup \sup
cot\cot \cot lg\lg \lg f\operatorname{f} \operatorname{f}

Functions on the right column of this table can take \limits.

9.5: \sqrt

x\sqrt{x} \sqrt{x}

x3\sqrt[3]{x} \sqrt[3]{x}

10: Relations

=!\stackrel{!}{=} \stackrel{!}{=}

== = \eqcirc \eqcirc \lesseqgtr \lesseqgtr \sqsupset \sqsupset
<< < \eqcolon \eqcolon \lesseqqgtr \lesseqqgtr \sqsupseteq \sqsupseteq
>> > \Eqcolon \Eqcolon \lessgtr \lessgtr \Subset \Subset
:: : \eqqcolon \eqqcolon \lesssim \lesssim \subset \subset or \sub
\approx \approx =\Eqqcolon \Eqqcolon \ll \ll \subseteq \subseteq or \sube
\approxeq \approxeq \eqsim \eqsim \lll \lll \subseteqq \subseteqq
\asymp \asymp \eqslantgtr \eqslantgtr \llless \llless \succ \succ
\backepsilon \backepsilon \eqslantless \eqslantless <\lt \lt \succapprox \succapprox
\backsim \backsim \equiv \equiv \mid \mid \succcurlyeq \succcurlyeq
\backsimeq \backsimeq \fallingdotseq \fallingdotseq \models \models \succeq \succeq
\between \between \frown \frown \multimap \multimap \succsim \succsim
\bowtie \bowtie \ge \ge \owns \owns \Supset \Supset
\bumpeq \bumpeq \geq \geq \parallel \parallel \supset \supset
\Bumpeq \Bumpeq \geqq \geqq \perp \perp \supseteq \supseteq or \supe
\circeq \circeq \geqslant \geqslant \pitchfork \pitchfork \supseteqq \supseteqq
:\colonapprox \colonapprox \gg \gg \prec \prec \thickapprox \thickapprox
\Colonapprox \Colonapprox \ggg \ggg \precapprox \precapprox \thicksim \thicksim
:\coloneq \coloneq \gggtr \gggtr \preccurlyeq \preccurlyeq \trianglelefteq \trianglelefteq
\Coloneq \Coloneq >\gt \gt \preceq \preceq \triangleq \triangleq
\coloneqq \coloneqq \gtrapprox \gtrapprox \precsim \precsim \trianglerighteq \trianglerighteq
=\Coloneqq \Coloneqq \gtreqless \gtreqless \propto \propto \varpropto \varpropto
:\colonsim \colonsim \gtreqqless \gtreqqless \risingdotseq \risingdotseq \vartriangle \vartriangle
\Colonsim \Colonsim \gtrless \gtrless \shortmid \shortmid \vartriangleleft \vartriangleleft
\cong \cong \gtrsim \gtrsim \shortparallel \shortparallel \vartriangleright \vartriangleright
\curlyeqprec \curlyeqprec \in \in or \isin \sim \sim :\vcentcolon \vcentcolon
\curlyeqsucc \curlyeqsucc \Join \Join \simeq \simeq \vdash \vdash
\dashv \dashv \le \le \smallfrown \smallfrown \vDash \vDash
\dblcolon \dblcolon \leq \leq \smallsmile \smallsmile \Vdash \Vdash
\doteq \doteq \leqq \leqq \smile \smile \Vvdash \Vvdash
\Doteq \Doteq \leqslant \leqslant \sqsubset \sqsubset
\doteqdot \doteqdot \lessapprox \lessapprox \sqsubseteq \sqsubseteq

Direct Input: =<>:= < > : ∈ ∋ ∝ ∼ ∽ ≂ ≃ ≅ ≈ ≊ ≍ ≎ ≏ ≐ ≑ ≒ ≓ ≖ ≗ ≜ ≡ ≤ ≥ ≦ ≧ ≫ ≬ ≳ ≷ ≺ ≻ ≼ ≽ ≾ ≿ ⊂ ⊃ ⊆ ⊇ ⊏ ⊐ ⊑ ⊒ ⊢ ⊣ ⊩ ⊪ ⊸ ⋈ ⋍ ⋐ ⋑ ⋔ ⋙ ⋛ ⋞ ⋟ ⌢ ⌣ ⩾ ⪆ ⪌ ⪕ ⪖ ⪯ ⪰ ⪷ ⪸ ⫅ ⫆ ≲ ⩽ ⪅ ≶ ⋚ ⪋ ⟂ ⊨ ≔ ≕ ⩴

10.1: Negated Relations

\not = \not =

\gnapprox \gnapprox \ngeqslant \ngeqslant \nsubseteq \nsubseteq \precneqq \precneqq
\gneq \gneq \ngtr \ngtr \nsubseteqq \nsubseteqq \precnsim \precnsim
\gneqq \gneqq \nleq \nleq \nsucc \nsucc \subsetneq \subsetneq
\gnsim \gnsim \nleqq \nleqq \nsucceq \nsucceq \subsetneqq \subsetneqq
\gvertneqq \gvertneqq \nleqslant \nleqslant \nsupseteq \nsupseteq \succnapprox \succnapprox
\lnapprox \lnapprox \nless \nless \nsupseteqq \nsupseteqq \succneqq \succneqq
\lneq \lneq \nmid \nmid \ntriangleleft \ntriangleleft \succnsim \succnsim
\lneqq \lneqq \notin \notin \ntrianglelefteq \ntrianglelefteq \supsetneq \supsetneq
\lnsim \lnsim \notni \notni \ntriangleright \ntriangleright \supsetneqq \supsetneqq
\lvertneqq \lvertneqq \nparallel \nparallel \ntrianglerighteq \ntrianglerighteq \varsubsetneq \varsubsetneq
\ncong \ncong \nprec \nprec \nvdash \nvdash \varsubsetneqq \varsubsetneqq
\ne \ne \npreceq \npreceq \nvDash \nvDash \varsupsetneq \varsupsetneq
\neq \neq \nshortmid \nshortmid \nVDash \nVDash \varsupsetneqq \varsupsetneqq
\ngeq \ngeq \nshortparallel \nshortparallel \nVdash \nVdash
\ngeqq \ngeqq \nsim \nsim \precnapprox \precnapprox

Direct Input:

∉ ∌ ∤ ∦ ≁ ≆ ≠ ≨ ≩ ≮ ≯ ≰ ≱ ⊀ ⊁ ⊈ ⊉ ⊊ ⊋ ⊬ ⊭ ⊮ ⊯ ⋠ ⋡ ⋦ ⋧ ⋨ ⋩ ⋬ ⋭ ⪇ ⪈ ⪉ ⪊ ⪵ ⪶ ⪹ ⪺ ⫋ ⫌

10.2: Arrows

\circlearrowleft \circlearrowleft \leftharpoonup \leftharpoonup \rArr \rArr
\circlearrowright \circlearrowright \leftleftarrows \leftleftarrows \rarr \rarr
\curvearrowleft \curvearrowleft \leftrightarrow \leftrightarrow \restriction \restriction
\curvearrowright \curvearrowright \Leftrightarrow \Leftrightarrow \rightarrow \rightarrow
\Darr \Darr \leftrightarrows \leftrightarrows \Rightarrow \Rightarrow
\dArr \dArr \leftrightharpoons \leftrightharpoons \rightarrowtail \rightarrowtail
\darr \darr \leftrightsquigarrow \leftrightsquigarrow \rightharpoondown \rightharpoondown
\dashleftarrow \dashleftarrow \Lleftarrow \Lleftarrow \rightharpoonup \rightharpoonup
\dashrightarrow \dashrightarrow \longleftarrow \longleftarrow \rightleftarrows \rightleftarrows
\downarrow \downarrow \Longleftarrow \Longleftarrow \rightleftharpoons \rightleftharpoons
\Downarrow \Downarrow \longleftrightarrow \longleftrightarrow \rightrightarrows \rightrightarrows
\downdownarrows \downdownarrows \Longleftrightarrow \Longleftrightarrow \rightsquigarrow \rightsquigarrow
\downharpoonleft \downharpoonleft \longmapsto \longmapsto \Rrightarrow \Rrightarrow
\downharpoonright \downharpoonright \longrightarrow \longrightarrow \Rsh \Rsh
\gets \gets \Longrightarrow \Longrightarrow \searrow \searrow
\Harr \Harr \looparrowleft \looparrowleft \swarrow \swarrow
\hArr \hArr \looparrowright \looparrowright \to \to
\harr \harr \Lrarr \Lrarr \twoheadleftarrow \twoheadleftarrow
\hookleftarrow \hookleftarrow \lrArr \lrArr \twoheadrightarrow \twoheadrightarrow
\hookrightarrow \hookrightarrow \lrarr \lrarr \Uarr \Uarr
    \iff \iff \Lsh \Lsh \uArr \uArr
    \impliedby \impliedby \mapsto \mapsto \uarr \uarr
    \implies \implies \nearrow \nearrow \uparrow \uparrow
\Larr \Larr \nleftarrow \nleftarrow \Uparrow \Uparrow
\lArr \lArr \nLeftarrow \nLeftarrow \updownarrow \updownarrow
\larr \larr \nleftrightarrow \nleftrightarrow \Updownarrow \Updownarrow
\leadsto \leadsto \nLeftrightarrow \nLeftrightarrow \upharpoonleft \upharpoonleft
\leftarrow \leftarrow \nrightarrow \nrightarrow \upharpoonright \upharpoonright
\Leftarrow \Leftarrow \nRightarrow \nRightarrow \upuparrows \upuparrows
\leftarrowtail \leftarrowtail \nwarrow \nwarrow
\leftharpoondown \leftharpoondown \Rarr \Rarr

Direct Input: ← ↑ → ↓ ↔ ↕ ↖ ↗ ↘ ↙ ↚ ↛ ↞ ↠ ↢ ↣ ↦ ↩ ↪ ↫ ↬ ↭ ↮ ↰ ↱↶ ↷ ↺ ↻ ↼ ↽ ↾ ↾ ↿ ⇀ ⇁ ⇂ ⇃ ⇄ ⇆ ⇇ ⇈ ⇉ ⇊ ⇋ ⇌⇍ ⇎ ⇏ ⇐ ⇑ ⇒ ⇓ ⇔ ⇕ ⇚ ⇛ ⇝ ⇠ ⇢ ⟵ ⟶ ⟷ ⟸ ⟹ ⟺ ⟼

Extensible Arrows

abc\xleftarrow{abc} \xleftarrow{abc} underover\xrightarrow[under]{over} \xrightarrow[under]{over}
abc\xLeftarrow{abc} \xLeftarrow{abc} abc\xRightarrow{abc} \xRightarrow{abc}
abc\xleftrightarrow{abc} \xleftrightarrow{abc} abc\xLeftrightarrow{abc} \xLeftrightarrow{abc}
abc\xhookleftarrow{abc} \xhookleftarrow{abc} abc\xhookrightarrow{abc} \xhookrightarrow{abc}
abc\xtwoheadleftarrow{abc} \xtwoheadleftarrow{abc} abc\xtwoheadrightarrow{abc} \xtwoheadrightarrow{abc}
abc\xleftharpoonup{abc} \xleftharpoonup{abc} abc\xrightharpoonup{abc} \xrightharpoonup{abc}
abc\xleftharpoondown{abc} \xleftharpoondown{abc} abc\xrightharpoondown{abc} \xrightharpoondown{abc}
abc\xleftrightharpoons{abc} \xleftrightharpoons{abc} abc\xrightleftharpoons{abc} \xrightleftharpoons{abc}
abc\xtofrom{abc} \xtofrom{abc} abc\xmapsto{abc} \xmapsto{abc}

|=abc\xlongequal{abc} \xlongequal{abc}

Extensible arrows all can take an optional argument in the same manner, as \xrightarrow[under]{over}.

11: Style, Color, Size, and Font

Class Assignment

  • \mathbin \mathclose \mathinner \mathop

  • \mathopen \mathord \mathpunct \mathrel

Color

F=ma\color{blue} F=ma \color{blue} F=ma

Note that KaTeX \color acts like a switch. This aligns with LaTeX and differs from MathJax. Other KaTeX color functions expect the content to be a function argument:

  • F=ma\textcolor{blue}{F=ma} \textcolor{blue}{F=ma}
  • F=ma\textcolor{#228B22}{F=ma} \textcolor{#228B22}{F=ma}
  • A\colorbox{aqua}{A} \colorbox{aqua}{A}
  • A\fcolorbox{red}{aqua}{A} \fcolorbox{red}{aqua}{A}

For color definition, KaTeX color functions will accept the standard HTML predefined color names. They will also accept an RGB argument in CSS hexa­decimal style. The "#" is optional before a six-digit specification.

Font

Ab0\mathrm{Ab0} \mathrm{Ab0} Ab0\mathbf{Ab0} \mathbf{Ab0} Ab\mathit{Ab} \mathit{Ab}
Ab0\mathnormal{Ab0} \mathnormal{Ab0} Ab0\textbf{Ab0} \textbf{Ab0} Ab\textit{Ab} \textit{Ab}
Ab0\textrm{Ab0} \textrm{Ab0} Ab0\bf Ab0 \bf Ab0 Ab\it Ab \it Ab
Ab0\rm Ab0 \rm Ab0 Ab0\bold{Ab0} \bold{Ab0} AB\Bbb{AB} \Bbb{AB}
Ab0\textnormal{Ab0} \textnormal{Ab0} Ab\boldsymbol{Ab} \boldsymbol{Ab} AB\mathbb{AB} \mathbb{AB}
Ab0\text{Ab0} \text{Ab0} Ab\bm{Ab} \bm{Ab} Ab0\frak{Ab0} \frak{Ab0}
Ab0\mathsf{Ab0} \mathsf{Ab0} Ab0\mathtt{Ab0} \mathtt{Ab0} Ab0\mathfrak{Ab0} \mathfrak{Ab0}
Ab0\textsf{Ab0} \textsf{Ab0} Ab0\texttt{Ab0} \texttt{Ab0} AB0\mathcal{AB0} \mathcal{AB0}
Ab0\sf Ab0 \sf Ab0 Ab0\tt Ab0 \tt Ab0 AB\mathscr{AB} \mathscr{AB}

One can stack font family, font weight, and font shape by using the \textXX versions of the font functions. So \textsf{\textbf{H}} will produce H\textsf{\textbf{H}}. The other versions do not stack, e.g., \mathsf{\mathbf{H}} will produce H\mathsf{\mathbf{H}}.

In cases where KaTeX fonts do not have a bold glyph, \pmb can simulate one. For example, \pmb{\mu} renders as : μ\pmb{\mu}

Size

AB\Huge AB \Huge AB AB\normalsize AB \normalsize AB
AB\huge AB \huge AB AB\small AB \small AB
AB\LARGE AB \LARGE AB AB\footnotesize AB \footnotesize AB
AB\Large AB \Large AB AB\scriptsize AB \scriptsize AB
AB\large AB \large AB AB\tiny AB \tiny AB

Style

|i=1n\displaystyle\sum_{i=1}^n \displaystyle\sum_{i=1}^n |i=1n\textstyle\sum_{i=1}^n \textstyle\sum_{i=1}^n |x\scriptstyle x \scriptstyle x         (The size of a first sub/superscript) |x\scriptscriptstyle x \scriptscriptstyle x (The size of subsequent sub/superscripts) |limx\lim\limits_x \lim\limits_x |limx\lim\nolimits_x \lim\nolimits_x |x^2\verb!x^2! \verb!x^2!

\text{…} will accept nested $…$ fragments and render them in math mode.

12: Symbols and Punctuation

% comment \dots \dots KaTeX\KaTeX \KaTeX
%\% \% \cdots \cdots LaTeX\LaTeX \LaTeX
#\# \# \ddots \ddots TeX\TeX \TeX
&\& \& \ldots \ldots \nabla \nabla
_\_ \_ \vdots \vdots \infty \infty
_\text{\textunderscore} \text{\textunderscore} \dotsb \dotsb \infin \infin
\text{--} \text{--} \dotsc \dotsc \checkmark \checkmark
\text{\textendash} \text{\textendash}  ⁣\dotsi \dotsi \dag \dag
\text{---} \text{---} \dotsm \dotsm \dagger \dagger
\text{\textemdash} \text{\textemdash} \dotso \dotso \text{\textdagger} \text{\textdagger}
~\text{\textasciitilde} \text{\textasciitilde} \sdot \sdot \ddag \ddag
` ` \mathellipsis \mathellipsis \ddagger \ddagger
\text{\textquoteleft} text{\textquoteleft} \text{\textellipsis} \text{\textellipsis} \text{\textdaggerdbl} \text{\textdaggerdbl}
\lq \lq \Box \Box \Dagger \Dagger
\text{\textquoteright} \text{\textquoteright} \square \square \angle \angle
\rq \rq \blacksquare \blacksquare \measuredangle \measuredangle
\text{\textquotedblleft} \text{\textquotedblleft} \triangle \triangle \sphericalangle \sphericalangle
"" " \triangledown \triangledown \top \top
\text{\textquotedblright} \text{\textquotedblright} \triangleleft \triangleleft \bot \bot
 ⁣:\colon \colon \triangleright \triangleright $\$ \$
\backprime \backprime \bigtriangledown \bigtriangledown $\text{\textdollar} \text{\textdollar}
\prime \prime \bigtriangleup \bigtriangleup £\pounds \pounds
<\text{\textless} \text{\textless} \blacktriangle \blacktriangle £\mathsterling \mathsterling
>\text{\textgreater} \text{\textgreater} \blacktriangledown \blacktriangledown £\text{\textsterling} \text{\textsterling}
|\text{\textbar} \text{\textbar} \blacktriangleleft \blacktriangleleft ¥\yen \yen
\text{\textbardbl} \text{\textbardbl} \blacktriangleright \blacktriangleright \surd \surd
{\text{\textbraceleft} \text{\textbraceleft} \diamond \diamond °\degree \degree
}\text{\textbraceright} \text{\textbraceright} \Diamond \Diamond °\text{\textdegree} \text{\textdegree}
\text{\P} \text{\P} \lozenge \lozenge \mho \mho
§\text{\S} \text{\S} \blacklozenge \blacklozenge \diagdown \diagdown
§\text{\sect} \text{\sect} \star \star \diagup \diagup
©\copyright \copyright \bigstar \bigstar \flat \flat
®\circledR \circledR \clubsuit \clubsuit \natural \natural
®\text{\textregistered} \text{\textregistered} \clubs \clubs \sharp \sharp
\circledS \circledS \diamondsuit \diamondsuit \heartsuit \heartsuit
a\text{\textcircled a} \text{\textcircled a} \diamonds \diamonds \hearts \hearts
\maltese \maltese \spadesuit \spadesuit \spades \spades

Direct Input: £¥!£ ¥ ∇ ∞ · ∠ ∡ ∢ ♠ ♡ ♢ ♣ ♭ ♮ ♯ ✓ … ⋮ ⋯ ⋱ !

13: Units

In KaTeX, units are proportioned as they are in TeX. KaTeX units are different than CSS units.

KaTeX Unit Value KaTeX Unit Value
em CSS em bp 1/72​ inch × F × G
ex CSS ex pc 12 KaTeX pt
mu 1/18 CSS em dd 1238/1157​ KaTeX pt
pt 1/72.27 inch × F × G cc 14856/1157 KaTeX pt
mm 1 mm × F × G nd 685/642 KaTeX pt
cm 1 cm × F × G nc 1370/107​ KaTeX pt
in 1 inch × F × G sp 1/65536 KaTeX pt

where:

  • F = (font size of surrounding HTML text)/(10 pt)

  • G = 1.21 by default, because KaTeX font-size is normally 1.21 × the surrounding font size. This value can be overridden by the CSS of an HTML page.

The effect of style and size:

Unit textstyle scriptscript huge
em or ex \rule{1em}{1em} \scriptscriptstyle\rule{1em}{1em} \huge\rule{1em}{1em}
mu \rule{18mu}{18mu} \scriptscriptstyle\rule{18mu}{18mu} \huge\rule{18mu}{18mu}
others \rule{10pt}{10pt} \scriptscriptstyle\rule{10pt}{10pt} \huge\rule{10pt}{10pt}
]]>
<![CDATA[KaTeX: Support table]]> https://note.toshiki.dev/application/markdown-it-katex/support-table https://note.toshiki.dev/application/markdown-it-katex/support-table Thu, 01 Jul 2021 00:00:00 GMT KaTeX: Support table

note

This is an direct shameful copy of the documentation pulled from KaTeX documentation, I do not own any of the content below on behalf of this part of the documentation, the table might be outdated as versions migrates, please also refer to KaTeX's official documentation.

Symbols

Symbol/Function Rendered Source or Comment
! n!n! n!
\! a ⁣ba\!b a\!b
# y2\def\bar#1{#1^2} \bar{y} \def\bar#1{#1^2} \bar{y}
\# #\#
% %this is a comment
\% %\%
& abcd\begin{matrix} a & b\cr c & d \end{matrix} \begin{matrix}
   a & b \\
   c & d
\end{matrix}
\& &\&
' '
\' aˊ\text{\'{a}} \text{\'{a}}
( ((
) ))
\(…\) ab\text{\(\frac a b\)} \text{\(\frac a b\)}
\ a ba\ b a\ b
\" a¨\text{\"{a}} \text{\"{a}}
\$ $\text{\textdollar}
\, aba\,\,{b} a\,\,{b}
\. a˙\text{\.{a}} \text{\.{a}}
\: aba\:\:{b} a\:\:{b}
\; a    ba\;\;{b} a\;\;{b}
_ xix_i x_i
\_ _\_
\` aˋ\text{\`{a}} \text{\'{a}}
< <<
\= aˉ\text{\={a}} \text{\\={a}}
> >>
\> aba\>\>{b} a\>\>{b}
[ [[
] ]]
{ a{a} {a}
} a{a} {a}
\{ {\{
\} }\}
| \vert
\| \Vert
~ no no no breaks\text{no~no~no~breaks} \text{no~no~no~breaks}
\~ a˜\text{\~{a}} \text{\\~{a}}
\\ abcd\begin{matrix} a & b\\ c & d\end{matrix} \begin{matrix}
   a & b \\
   c & d
\end{matrix}
^ xix^i x^i
\^ aˆ\text{\^{a}} \text{\\^{a}}

A

Symbol/Function Rendered Source or Comment
\AA A˚\text{\AA} \text{\AA}
\aa a˚\text{\aa} \text{\aa}
\above ab+1{a \above{2pt} b+1} {a \above{2pt} b+1}
\abovewithdelims Not supported
\acute eˊ\acute e \acute e
\AE Æ\text{\AE} \text{\AE}
\ae æ\text{\ae} \text{\ae}
\alef \alef
\alefsym \alefsym
\aleph \aleph
Not supported see {aligned}
a=b+cd+e=f\begin{aligned}a&=b+c\\d+e&=f\end{aligned} \begin{aligned}
   a&=b+c \\
   d+e&=f
\end{aligned}
Not supported see {alignedat}
10x+3y=23x+13y=4\begin{alignedat}{2}10&x+&3&y=2\\3&x+&13&y=4\end{alignedat} \begin{alignedat}{2}
   10&x+ &3&y = 2 \\
    3&x+&13&y = 4
\end{alignedat}
\allowbreak
\Alpha A\Alpha
\alpha α\alpha
\amalg ⨿\amalg
\And &\And
\and Not supported Deprecated
\ang Not supported Deprecated
\angl Not supported
\angle \angle
\approx \approx
\approxeq \approxeq
\arccos arccos\arccos
\arcctg arcctg\arcctg
\arcsin arcsin\arcsin
\arctan arctan\arctan
\arctg arctg\arctg
\arg arg\arg
\argmax arg max\argmax
\argmin arg min\argmin
abcd\begin{array}{cc}a&b\\c&d\end{array} \begin{array}{cc}
   a & b \\
   c & d
\end{array}
\array Not supported see {array}
\arraystretch abcd\def\arraystretch{1.5}\begin{array}{cc}a&b\\c&d\end{array} \def\arraystretch{1.5}
\begin{array}{cc}
   a & b \\
   c & d
\end{array}
\Arrowvert Not supported
\arrowvert Not supported
\ast \ast
\asymp \asymp
\atop ab{a \atop b} {a \atop b}
\atopwithdelims Not supported

B

| Symbol/Function | Rendered | Source or Comment | | :------------------ | :-------------------------------------------------- | :------------------------------------------------------------------------------------------------ | ------ | | \backepsilon | \backepsilon | | | \backprime | \backprime | | | \backsim | \backsim | | | \backsimeq | \backsimeq | | | \backslash | \\backslash | | | \bar | yˉ\bar{y} | \bar{y} | | \barwedge | \barwedge | | | \Bbb | ABC\Bbb{ABC} | \Bbb{ABC}
KaTeX supports A-Z & k | | \Bbbk | k\Bbbk | | | \bbox | Not supported | | | \bcancel | 5\bcancel{5} | \bcancel{5} | | \because | \because | | | \begin | abcd\begin{matrix} a & b\\ c & d\end{matrix} | \begin{matrix}
   a & b \\
   c & d
\end{matrix} | | \begingroup | \begingroup a} | \begingroup a} | | \Beta | B\Beta | | | \beta | β\beta | | | \beth | \beth | | | \between | \between | | | \bf | AaBb12\bf AaBb12 | \bf AaBb12 | | \bfseries | Not supported | | | \big | ()\big(\big) | \big(\big) | | \Big | ()\Big(\Big) | \Big(\Big) | | \bigcap | \bigcap | | | \bigcirc | \bigcirc | | | \bigcup | \bigcup | | | \bigg | ()\bigg(\bigg) | \bigg(\bigg) | | \Bigg | ()\Bigg(\Bigg) | \Bigg(\Bigg) | | \biggl | (\biggl( | \biggl( | | \Biggl | (\Biggl( | \Biggl( | | \biggm | \biggm\vert | \biggm\vert | | \Biggm | \Biggm\vert | \Biggm\vert | | \biggr | )\biggr) | \biggr) | | \Biggr | )\Biggr) | \Biggr) | | \bigl | (\bigl( | \bigl( | | \Bigl | (\Bigl( | \Bigl( | | \bigm | \bigm\vert | \bigm\vert | | \Bigm | \Bigm\vert | \Bigm\vert | | \bigodot | \bigodot | | | \bigominus | Not supported | Issue #1222 | | \bigoplus | \bigoplus | | | \bigoslash | Not supported | Issue #1222 | | \bigotimes | \bigotimes | | | \bigr | )\bigr) | \bigr) | | \Bigr | )\Bigr) | \Bigr) | | \bigsqcap | Not supported | Issue #1222 | | \bigsqcup | \bigsqcup | | | \bigstar | \bigstar | | | \bigtriangledown | \bigtriangledown | | | \bigtriangleup | \bigtriangleup | | | \biguplus | \biguplus | | | \bigvee | \bigvee | | | \bigwedge | \bigwedge | | | \binom | (nk)\binom n k | \binom n k | | \blacklozenge | \blacklozenge | | | \blacksquare | \blacksquare | | | \blacktriangle | \blacktriangle | | | \blacktriangledown | \blacktriangledown | | | \blacktriangleleft | \blacktriangleleft | | | \blacktriangleright | \blacktriangleright | | | \bm | AaBb\bm{AaBb} | \bm{AaBb} | | {Bmatrix} | {abcd}\begin{Bmatrix}a&b\\c&d\end{Bmatrix} | \begin{Bmatrix}
   a & b \\
   c & d
\end{Bmatrix} | | {bmatrix} | [abcd]\begin{bmatrix}a&b\\c&d\end{bmatrix} | \begin{bmatrix}
   a & b \\
   c & d
\end{bmatrix} | | \bmod | amodba \bmod b | a \bmod b | | \bold | AaBb123\bold{AaBb123} | \bold{AaBb123} | | \boldsymbol | AaBb\boldsymbol{AaBb} | \boldsymbol{AaBb} | | \bot | \bot | | | \bowtie | \bowtie | | | \Box | \Box | | | \boxdot | \boxdot | | | \boxed | ab\boxed{ab} | \boxed{ab} | | \boxminus | \boxminus | | | \boxplus | \boxplus | | | \boxtimes | \boxtimes | | | \Bra | ψ\left\langle\psi\right\| | \Bra{\psi} | | \bra | ψ\mathinner{\langle{\psi}\|} | \bra{\psi} | | \braket | ϕψ\mathinner{\langle{\phi\|\psi}\rangle} | \braket{\phi | \psi} | | \brace | {nk}{n\brace k} | {n\brace k} | | \bracevert | Not supported | | | \brack | [nk]{n\brack k} | {n\brack k} | | \breve | eu˘\breve{eu} | \breve{eu} | | \buildrel | Not supported | | | \bull | \bull | | | \bullet | \bullet | | | \Bumpeq | \Bumpeq | | | \bumpeq | \bumpeq | |

C

Symbol/Function Rendered Source or Comment
\C Not supported Deprecated
\cal AaBb123\cal AaBb123 \cal AaBb123
\cancel 5\cancel{5} \cancel{5}
\cancelto Not supported
\Cap \Cap
\cap \cap
{aif bcif d\begin{cases}a&\text{if }b\\c&\text{if }d\end{cases} \begin{cases}
   a &\text{if } b \\
   c &\text{if } d
\end{cases}
\cases Not supported see {cases}
Not supported
\cdot \cdot
\cdotp \cdotp
\cdots \cdots
\ce CX6HX5CHO{\mathrm{C}{\vphantom{X}}_{\smash[t]{6}}\mathrm{H}{\vphantom{X}}_{\smash[t]{5}}{-}\mathrm{CHO}}
\ce{C6H5-CHO}
{\mathrm{C}{\vphantom{X}}_{\smash[t]{6}}\mathrm{H}{\vphantom{X}}_{\smash[t]{5}}{-}\mathrm{CHO}}
or \ce{C6H5-CHO} Requires an extension
\cee Not supported Deprecated by mhchem
\centerdot aba\centerdot b a\centerdot b
\cf Not supported Deprecated by mhchem;
use \ce instead
\cfrac 21+21+21\cfrac{2}{1+\cfrac{2}{1+\cfrac{2}{1}}} \cfrac{2}{1+\cfrac{2}{1+\cfrac{2}{1}}}
\check oeˇ\check{oe} \check{oe}
\ch ch\ch
\checkmark \checkmark
\Chi X\Chi
\chi χ\chi
\choose (n+1k+2){n+1 \choose k+2} {n+1 \choose k+2}
\circ \circ
\circeq \circeq
\circlearrowleft \circlearrowleft
\circlearrowright \circlearrowright
\circledast \circledast
\circledcirc \circledcirc
\circleddash \circleddash
\circledR ®\circledR
\circledS \circledS
\class Not supported A PR is pending.
\cline Not supported Issue #269
\clubs \clubs
\clubsuit \clubsuit
\cnums C\cnums
\colon  ⁣:\colon
\Colonapprox \Colonapprox
\colonapprox :\colonapprox
\Coloneq \Coloneq
\coloneq :\coloneq
\Coloneqq =\Coloneqq
\coloneqq \coloneqq
\Colonsim \Colonsim
\colonsim :\colonsim
\color AaBb123\color{#0000FF} AaBb123 \color{#0000FF} AaBb123
\colorbox Black on red\colorbox{red}{Black on red} \colorbox{red}{Black on red}
\complement \complement
\Complex C\Complex
\cong \cong
\Coppa Not supported
\coppa Not supported
\coprod \coprod
\copyright ©\copyright
\cos cos\cos
\cosec cosec\cosec
\cosh cosh\cosh
\cot cot\cot
\cotg cotg\cotg
\coth coth\coth
\cr abcd\begin{matrix} a & b\cr c & d \end{matrix} \begin{matrix}
   a & b \cr
   c & d
\end{matrix}
\csc csc\csc
\cssId Not supported A PR is pending.
\ctg ctg\ctg
\cth cth\cth
\Cup \Cup
\cup \cup
\curlyeqprec \curlyeqprec
\curlyeqsucc \curlyeqsucc
\curlyvee \curlyvee
\curlywedge \curlywedge
\curvearrowleft \curvearrowleft
\curvearrowright \curvearrowright

D

Symbol/Function Rendered Source or Comment
\dag \dag
\Dagger \Dagger
\dagger \dagger
\daleth \daleth
\Darr \Darr
\dArr \dArr
\darr \darr
abcd\begin{darray}{cc}a&b\\c&d\end{darray} \begin{darray}{cc}
   a & b \\
   c & d
\end{darray}
\dashleftarrow \dashleftarrow
\dashrightarrow \dashrightarrow
\dashv \dashv
\dbinom (nk)\dbinom n k \dbinom n k
\dblcolon \dblcolon
{aif bcif d\begin{dcases}a&\text{if }b\\c&\text{if }d\end{dcases} \begin{dcases}
   a &\text{if } b \\
   c &\text{if } d
\end{dcases}
\ddag \ddag
\ddagger \ddagger
\ddddot Not supported
\dddot Not supported
\ddot x¨\ddot x \ddot x
\ddots \ddots
\DeclareMathOperator Not supported
\def x2+x2\def\foo{x^2} \foo + \foo \def\foo{x^2} \foo + \foo
\definecolor Not supported Issue #750
\deg deg\deg
\degree °\degree
\delta δ\delta
\Delta Δ\Delta
\det det\det
\Digamma Not supported
\digamma ϝ\digamma
\dfrac a1b1\dfrac{a-1}{b-1} \dfrac{a-1}{b-1}
\diagdown \diagdown
\diagup \diagup
\Diamond \Diamond
\diamond \diamond
\diamonds \diamonds
\diamondsuit \diamondsuit
\dim dim\dim
\displaylines Not supported
\displaystyle 0n\displaystyle\sum_0^n \displaystyle\sum_0^n
\div ÷\div
\divideontimes \divideontimes
\dot x˙\dot x \dot x
\Doteq \Doteq
\doteq \doteq
\doteqdot \doteqdot
\dotplus \dotplus
\dots x1++xnx_1 + \dots + x_n x_1 + \dots + x_n
\dotsb x1++xnx_1 +\dotsb + x_n x_1 +\dotsb + x_n
\dotsc x,,yx,\dotsc,y x,\dotsc,y
\dotsi $$\int_{A_1}\int_{A_2}\dotsi$$ \int_{A_1}\int_{A_2}\dotsi
\dotsm x1x2xnx_1 x_2 \dotsm x_n $x_1 x_2 \dotsm x_n
\dotso \dotso
\doublebarwedge \doublebarwedge
\doublecap \doublecap
\doublecup \doublecup
\Downarrow \Downarrow
\downarrow \downarrow
\downdownarrows \downdownarrows
\downharpoonleft \downharpoonleft
\downharpoonright \downharpoonright
aif bcif d}\begin{drcases}a&\text{if }b\\c&\text{if }d\end{drcases} \begin{drcases}
   a &\text{if } b \\
   c &\text{if } d
\end{drcases}

E

Symbol/Function Rendered Source or Comment
\edef a\def\foo{a}\edef\bar{\foo}\def\foo{}\bar \def\foo{a}\edef\bar{\foo}\def\foo{}\bar
\ell \ell
\else Not supported Issue #1003
\em Not supported
\emph Not supported
\empty \empty
\emptyset \emptyset
\enclose Not supported Non standard
\end abcd\begin{matrix} a & b\\ c & d\end{matrix} \begin{matrix}
   a & b \\
   c & d
\end{matrix}
\endgroup {a\endgroup {a\endgroup
\enspace aba\enspace b a\enspace b
\Epsilon E\Epsilon
\epsilon ϵ\epsilon
\eqalign Not supported
\eqalignno Not supported
\eqcirc \eqcirc
\Eqcolon \Eqcolon
\eqcolon \eqcolon
Not supported Issue #445
Not supported
\Eqqcolon =\Eqqcolon
\eqqcolon \eqqcolon
\eqref Not supported Issue #350
\eqsim \eqsim
\eqslantgtr \eqslantgtr
\eqslantless \eqslantless
\equiv \equiv
\Eta H\Eta
\eta η\eta
\eth ð\eth
\euro Not supported
\exist \exist
\exists \exists
\exp exp\exp
\expandafter

F

Symbol/Function Rendered Source or Comment
\fallingdotseq \fallingdotseq
\fbox Hi there!\fbox{Hi there!} \fbox{Hi there!}
\fcolorbox A\fcolorbox{red}{aqua}{A} \fcolorbox{red}{aqua}{A}
\fi Not supported Issue #1003
\Finv \Finv
\flat \flat
\footnotesize footnotesize\footnotesize footnotesize \footnotesize footnotesize
\forall \forall
\frac ab\frac a b \frac a b
\frak AaBb\frak{AaBb} \frak{AaBb}
\frown \frown
\futurelet

G

Symbol/Function Rendered Source or Comment
\Game \Game
\Gamma Γ\Gamma
\gamma γ\gamma
Not supported see {gathered}
a=be=b+c\begin{gathered}a=b\\e=b+c\end{gathered} \begin{gathered}
   a=b \\
   e=b+c
\end{gathered}
\gcd gcd\gcd
\gdef y2+y2\gdef\bar#1{#1^2} \bar{y} + \bar{y} \gdef\bar#1{#1^2} \bar{y} + \bar{y}
\ge \ge
\geneuro Not supported
\geneuronarrow Not supported
\geneurowide Not supported
\genfrac (aa+1]\genfrac ( ] {2pt}{0}a{a+1} \genfrac ( ] {2pt}{0}a{a+1}
\geq \geq
\geqq \geqq
\geqslant \geqslant
\gets \gets
\gg \gg
\ggg \ggg
\gggtr \gggtr
\gimel \gimel
\global 2+3\global\def\add#1#2{#1+#2} \add 2 3 \global\def\add#1#2{#1+#2} \add 2 3
\gnapprox \gnapprox
\gneq \gneq
\gneqq \gneqq
\gnsim \gnsim
\grave euˋ\grave{eu} \grave{eu}
\gt a>ba \gt b a \gt b
\gtrdot \gtrdot
\gtrapprox \gtrapprox
\gtreqless \gtreqless
\gtreqqless \gtreqqless
\gtrless \gtrless
\gtrsim \gtrsim
\gvertneqq \gvertneqq

H

Symbol/Function Rendered Source or Comment
\H a˝\text{\H{a}} \text{\H{a}}
\Harr \Harr
\hArr \hArr
\harr \harr
\hat θ^\hat{\theta} \hat{\theta}
\hbar \hbar
\hbox Not supported
\hdashline abcd\begin{matrix}a&b\\ \hdashline c &d\end{matrix} \begin{matrix}
   a & b \\
   \hdashline
   c & d
\end{matrix}
\hearts \hearts
\heartsuit \heartsuit
\hfil Not supported
\hfill Not supported Issues #164 & #269
\hline abcd\begin{matrix}a&b\\ \hline c &d\end{matrix} \begin{matrix}
   a & b \\ \hline
   c & d
\end{matrix}
\hom hom\hom
\hookleftarrow \hookleftarrow
\hookrightarrow \hookrightarrow
\hphantom abcda\hphantom{bc}d a\hphantom{bc}d
\href \href\href{https://katex.org/}{\KaTeX} \href{https://katex.org/}{\KaTeX} Requires trust
\hskip widw\hskip1em i\hskip2em d w\hskip1em i\hskip2em d
\hslash \hslash
\hspace s\hspace7ex k s\hspace7ex k
\htmlClass \htmlClass\htmlClass{foo}{x} \htmlClass{foo}{x} Must enable trust and disable strict
\htmlData \htmlData\htmlData{foo=a, bar=b}{x} \htmlData{foo=a, bar=b}{x} Must enable trust and disable strict
\htmlId \htmlId\htmlId{bar}{x} \htmlId{bar}{x} Must enable trust and disable strict
\htmlStyle \htmlStyle\htmlStyle{color: red;}{x} \htmlStyle{color: red;}{x} Must enable trust and disable strict
\huge huge\huge huge \huge huge
\Huge Huge\Huge Huge \Huge Huge

I

Symbol/Function Rendered Source or Comment
\i ı\text{\i} \text{\i}
\idotsint Not supported
\iddots Not supported Issue #1223
\if Not supported Issue #1003
\iff A    BA\iff B A\iff B
\ifmode Not supported Issue #1003
\ifx Not supported Issue #1003
\iiiint Not supported
\iiint \iiint
\iint \iint
\Im \Im
\image \image
\imath ı\imath
\impliedby P    QP\impliedby Q P\impliedby Q
\implies P    QP\implies Q P\implies Q
\in \in
\includegraphics \includegraphics\includegraphics[height=0.8em, totalheight=0.9em, width=0.9em, alt=KA logo]{https://cdn.kastatic.org/images/apple-touch-icon-57x57-precomposed.new.png} \includegraphics[height=0.8em, totalheight=0.9em, width=0.9em, alt=KA logo]{https://cdn.kastatic.org/images/apple-touch-icon-57x57-precomposed.new.png} Requires trust
\inf inf\inf
\infin \infin
\infty \infty
\injlim Not supported
\int \int
\intercal \intercal
\intop \intop
\Iota I\Iota
\iota ι\iota
\isin \isin
\it AaBb{\it AaBb} {\it AaBb}
\itshape Not supported

JK

Symbol/Function Rendered Source or Comment
\j ȷ\text{\j} \text{\j}
\jmath ȷ\jmath
\Join \Join
\Kappa K\Kappa
\kappa κ\kappa
\KaTeX KaTeX\KaTeX
\ker ker\ker
\kern IRI\kern-2.5pt R I\kern-2.5pt R
\Ket ψ\left|\psi\right\rangle \Ket{\psi}
\ket ψ\mathinner{|{\psi}\rangle} \ket{\psi}
\Koppa Not supported
\koppa Not supported

L

Symbol/Function Rendered Source or Comment
\L Not supported
\l Not supported
\Lambda Λ\Lambda
\lambda λ\lambda
\label Not supported
\land \land
\lang A\lang A\rangle \lang A\rangle
\langle A\langle A\rangle \langle A\rangle
\Larr \Larr
\lArr \lArr
\larr \larr
\large large\large large \large large
\Large Large\Large Large \Large Large
\LARGE LARGE\LARGE LARGE \LARGE LARGE
\LaTeX LaTeX\LaTeX
\lBrace \lBrace
\lbrace {\lbrace
\lbrack [\lbrack
\lceil \lceil
\ldotp .\ldotp
\ldots \ldots
\le \le
\leadsto \leadsto
\left {ab\left\lbrace \dfrac ab \right. \left\lbrace \dfrac ab \right.
\leftarrow \leftarrow
\Leftarrow \Leftarrow
\LeftArrow Not supported Non standard
\leftarrowtail Not supported
\leftharpoondown \leftharpoondown
\leftharpoonup \leftharpoonup
\leftleftarrows \leftleftarrows
\Leftrightarrow \Leftrightarrow
\leftrightarrow \leftrightarrow
\leftrightarrows \leftrightarrows
\leftrightharpoons \leftrightharpoons
\leftrightsquigarrow \leftrightsquigarrow
\leftroot Not supported
\leftthreetimes \leftthreetimes
\leq \leq
\leqalignno Not supported
\leqq \leqq
\leqslant \leqslant
\lessapprox \lessapprox
\lessdot \lessdot
\lesseqgtr \lesseqgtr
\lesseqqgtr \lesseqqgtr
\lessgtr \lessgtr
\lesssim \lesssim
\let
\lfloor \lfloor
\lg lg\lg
\lgroup \lgroup
\lhd \lhd
\lim lim\lim
\liminf lim inf\liminf
\limits limx\lim\limits_x \lim\limits_x
\limsup lim sup\limsup
\ll \ll
\llap =/{=}\llap{/\,} {=}\llap{/\,}
\llbracket \llbracket
\llcorner \llcorner
\Lleftarrow \Lleftarrow
\lll \lll
\llless \llless
\lmoustache \lmoustache
\ln ln\ln
\lnapprox \lnapprox
\lneq \lneq
\lneqq \lneqq
\lnot ¬\lnot
\lnsim \lnsim
\log log\log
\long
\Longleftarrow \Longleftarrow
\longleftarrow \longleftarrow
\Longleftrightarrow \Longleftrightarrow
\longleftrightarrow \longleftrightarrow
\longmapsto \longmapsto
\Longrightarrow \Longrightarrow
\longrightarrow \longrightarrow
\looparrowleft \looparrowleft
\looparrowright \looparrowright
\lor \lor
\lower Not supported
\lozenge \lozenge
\lparen (\lparen
\Lrarr \Lrarr
\lrArr \lrArr
\lrarr \lrarr
\lrcorner \lrcorner
\lq \lq
\Lsh \Lsh
\lt <\lt
\ltimes \ltimes
\lVert \lVert
\lvert \lvert
\lvertneqq \lvertneqq

M

Symbol/Function Rendered Source or Comment
\maltese \maltese
\mapsto \mapsto
\mathbb AB\mathbb{AB} \mathbb{AB}
KaTeX supports A-Z k
\mathbf AaBb123\mathbf{AaBb123} \mathbf{AaBb123}
\mathbin a!ba\mathbin{!}b a\mathbin{!}b
\mathcal AaBb123\mathcal{AaBb123} \mathcal{AaBb123}
\mathchoice aba\mathchoice{\,}{\,\,}{\,\,\,}{\,\,\,\,}b a\mathchoice{\,}{\,\,}{\,\,\,}{\,\,\,\,}b
\mathclap 1inxi\displaystyle\sum_{\mathclap{1\le i\le n}} x_{i} \sum_{\mathclap{1\le i\le n}} x_{i}
\mathclose a+(b>+ca + (b\mathclose\gt + c a + (b\mathclose\gt + c
\mathellipsis \mathellipsis
\mathfrak AaBb\mathfrak{AaBb} \mathfrak{AaBb}
KaTeX supports A-Za-z
\mathinner abinsidecdab\mathinner{\text{inside}}cd ab\mathinner{\text{inside}}cd
\mathit AaBb\mathit{AaBb} \mathit{AaBb}
KaTeX supports A-Za-z
\mathllap =/{=}\mathllap{/\,} {=}\mathllap{/\,}
\mathnormal AaBb\mathnormal{AaBb} \mathnormal{AaBb}
KaTeX supports A-Za-z
\mathop ab\mathop{\star}_a^b \mathop{\star}_a^b
\mathopen a+<b)+ca + \mathopen\lt b) + c a + \mathopen\lt b) + c
\mathord 1,234,5671\mathord{,}234{,}567 1\mathord{,}234{,}567
\mathpunct ABA\mathpunct{-}B A\mathpunct{-}B
\mathrel a#ba \mathrel{\#} b a \mathrel{\#} b
\mathrlap /=\mathrlap{\,/}{=} \mathrlap{\,/}{=}
\mathring a˚\mathring{a} \mathring{a}
\mathrm AaBb123\mathrm{AaBb123} \mathrm{AaBb123}
\mathscr AB\mathscr{AB} \mathscr{AaBb123}
KaTeX supports A-Z
\mathsf AaBb123\mathsf{AaBb123} \mathsf{AaBb123}
\mathsterling £\mathsterling
\mathstrut Not supported
\mathtip Not supported
\mathtt AaBb123\mathtt{AaBb123} \mathtt{AaBb123}
\matrix Not supported See {matrix}
abcd\begin{matrix}a&b\\c&d\end{matrix} \begin{matrix}
   a & b \\
   c & d
\end{matrix}
\max max\max
\mbox Not supported
\md Not supported
\mdseries Not supported
\measuredangle \measuredangle
\medspace aba\medspace b a\medspace b
\mho \mho
\mid {xRx>0}\{x∈ℝ\mid x>0\} \{x∈ℝ\mid x>0\}
\middle P(A|B)P\left(A\middle\vert B\right) P\left(A\middle\vert B\right)
\min min\min
\mit Not supported See \mathit
\mkern aba\mkern18mu b a\mkern18mu b
\mmlToken Not supported
\mod 35mod23\equiv 5 \mod 2 3\equiv 5 \mod 2
\models \models
\moveleft Not supported
\moveright Not supported
\mp \mp
\mskip aba\mskip{10mu}b a\mskip{10mu}b
\mspace Not supported
\Mu M\Mu
\mu μ\mu
\multicolumn Not supported Issue #269
Not supported
\multimap \multimap

N

Symbol/Function Rendered Source or Comment
\N N\N
\nabla \nabla
\natnums N\natnums
\natural \natural
\negmedspace a ⁣ba\negmedspace b a\negmedspace b
\ncong \ncong
\ne \ne
\nearrow \nearrow
\neg ¬\neg
\negthickspace a ⁣ba\negthickspace b a\negthickspace b
\negthinspace a ⁣ba\negthinspace b a\negthinspace b
\neq \neq
\newcommand \newcommand\chk{\checkmark} \chk \newcommand\chk{\checkmark} \chk
\newenvironment Not supported Issue #37
\Newextarrow Not supported
\newline aba\newline b a\newline b
\nexists \nexists
\ngeq \ngeq
\ngeqq \ngeqq
\ngeqslant \ngeqslant
\ngtr \ngtr
\ni \ni
\nleftarrow \nleftarrow
\nLeftarrow \nLeftarrow
\nLeftrightarrow \nLeftrightarrow
\nleftrightarrow \nleftrightarrow
\nleq \nleq
\nleqq \nleqq
\nleqslant \nleqslant
\nless \nless
\nmid \nmid
\nobreak
\nobreakspace a ba\nobreakspace b a\nobreakspace b
\noexpand
\nolimits limx\lim\nolimits_x \lim\nolimits_x
\normalfont Not supported
\normalsize normalsize\normalsize normalsize \normalsize normalsize
\not \not = \not =
\notag Not supported
\notin \notin
\notni \notni
\nparallel \nparallel
\nprec \nprec
\npreceq \npreceq
\nRightarrow \nRightarrow
\nrightarrow \nrightarrow
\nshortmid \nshortmid
\nshortparallel \nshortparallel
\nsim \nsim
\nsubseteq \nsubseteq
\nsubseteqq \nsubseteqq
\nsucc \nsucc
\nsucceq \nsucceq
\nsupseteq \nsupseteq
\nsupseteqq \nsupseteqq
\ntriangleleft \ntriangleleft
\ntrianglelefteq \ntrianglelefteq
\ntriangleright \ntriangleright
\ntrianglerighteq \ntrianglerighteq
\Nu N\Nu
\nu ν\nu
\nVDash \nVDash
\nVdash \nVdash
\nvDash \nvDash
\nvdash \nvdash
\nwarrow \nwarrow

O

Symbol/Function Rendered Source or Comment
\O Ø\text{\O} \text{\O}
\o ø\text{\o} \text{\o}
\odot \odot
\OE Œ\text{\OE} \text{\OE}
\oe œ\text{\oe} \text{\oe}
\officialeuro Not supported
\oiiint \oiiint
\oiint \oiint
\oint \oint
\oldstyle Not supported
\omega ω\omega
\Omega Ω\Omega
\Omicron O\Omicron
\omicron ο\omicron
\ominus \ominus
\operatorname asinx\operatorname{asin} x \operatorname{asin} x
\operatorname* asinyx\operatorname{asin}\limits_y x \operatorname{asin}\limits_y x
\oplus \oplus
\or Not supported
\oslash \oslash
\otimes \otimes
\over a+1b+2+c{a+1 \over b+2}+c {a+1 \over b+2}+c
\overbrace x++xn times\overbrace{x+⋯+x}^{n\text{ times}} \overbrace{x+⋯+x}^{n\text{ times}}
\overbracket Not supported
\overgroup AB\overgroup{AB} \overgroup{AB}
\overleftarrow AB\overleftarrow{AB} \overleftarrow{AB}
\overleftharpoon AB\overleftharpoon{AB} \overleftharpoon{AB}
\overleftrightarrow AB\overleftrightarrow{AB} \overleftrightarrow{AB}
\overline a long argument\overline{\text{a long argument}} \overline{\text{a long argument}}
\overlinesegment ABundefined\overlinesegment{AB} \overlinesegment{AB}
\overparen Not supported See \overgroup
\Overrightarrow AB\Overrightarrow{AB} \Overrightarrow{AB}
\overrightarrow AB\overrightarrow{AB} \overrightarrow{AB}
\overrightharpoon ac\overrightharpoon{ac} \overrightharpoon{ac}
\overset =!\overset{!}{=} \overset{!}{=}
\overwithdelims Not supported
\owns \owns

P

Symbol/Function Rendered Source or Comment
\P \text{\P} \text{\P}
\pagecolor Not supported Deprecated
\parallel \parallel
\part Not supported Deprecated
\partial \partial
\perp \perp
\phantom Γijkij\Gamma^{\phantom{i}j}_{i\phantom{j}k} \Gamma^{\phantom{i}j}_{i\phantom{j}k}
\phase Not supported
\Phi Φ\Phi
\phi ϕ\phi
\Pi Π\Pi
\pi π\pi
Not supported
\pitchfork \pitchfork
\plim plim\plim
\plusmn ±\plusmn
\pm ±\pm
\pmatrix Not supported See {pmatrix}
(abcd)\begin{pmatrix}a&b\\c&d\end{pmatrix} \begin{pmatrix}
   a & b \\
   c & d
\end{pmatrix}
\pmb μ\pmb{\mu} \pmb{\mu}
\pmod x(moda)x\pmod a x\pmod a
\pod x(a)x \pod a x \pod a
\pounds £\pounds
\Pr Pr\Pr
\prec \prec
\precapprox \precapprox
\preccurlyeq \preccurlyeq
\preceq \preceq
\precnapprox \precnapprox
\precneqq \precneqq
\precnsim \precnsim
\precsim \precsim
\prime \prime
\prod \prod
\projlim Not supported
\propto \propto
\providecommand Hello\providecommand\greet{\text{Hello}} \greet \providecommand\greet{\text{Hello}} \greet
\psi ψ\psi
\Psi Ψ\Psi
\pu 123 kJmol{123~\mathchoice{\textstyle\frac{\mathrm{kJ}}{\mathrm{mol}}}{\frac{\mathrm{kJ}}{\mathrm{mol}}}{\frac{\mathrm{kJ}}{\mathrm{mol}}}{\frac{\mathrm{kJ}}{\mathrm{mol}}}} \pu{123 kJ//mol} Requires an extension

QR

Symbol/Function Rendered Source or Comment
\Q Not supported See \Bbb{Q}
\qquad aba\qquad\qquad{b} a\qquad\qquad{b}
\quad aba\quad\quad{b} a\quad\quad{b}
\R R\R
\r a˚\text{\r{a}} \text{\r{a}}
\raise Not supported see \raisebox
\raisebox higherh\raisebox{2pt}{ighe}r h\raisebox{2pt}{ighe}r
\rang A\langle A\rang \langle A\rang
\rangle A\langle A\rangle \langle A\rangle
\Rarr \Rarr
\rArr \rArr
\rarr \rarr
\rBrace \rBrace
\rbrace }\rbrace
\rbrack ]\rbrack
aif bcif d}\begin{rcases}a&\text{if }b\\c&\text{if }d\end{rcases} \begin{rcases}
   a &\text{if } b \\
   c &\text{if } d
\end{rcases}
\rceil \rceil
\Re \Re
\real \real
\Reals R\Reals
\reals R\reals
\ref Not supported Issue #350
\relax
\renewcommand Ahoy!\def\hail{Hi!}\renewcommand\hail{\text{Ahoy!}} \hail \def\hail{Hi!}
\renewcommand\hail{\text{Ahoy!}}
\hail
\renewenvironment Not supported
\require Not supported
\restriction \restriction
\rfloor \rfloor
\rgroup \rgroup
\rhd \rhd
\Rho P\Rho
\rho ρ\rho
\right ab)\left.\dfrac a b\right) \left.\dfrac a b\right)
\Rightarrow \Rightarrow
\rightarrow \rightarrow
\rightarrowtail \rightarrowtail
\rightharpoondown \rightharpoondown
\rightharpoonup \rightharpoonup
\rightleftarrows \rightleftarrows
\rightleftharpoons \rightleftharpoons
\rightrightarrows \rightrightarrows
\rightsquigarrow \rightsquigarrow
\rightthreetimes \rightthreetimes
\risingdotseq \risingdotseq
\rlap /=\rlap{\,/}{=} \rlap{\,/}{=}
\rm AaBb12\rm AaBb12 \rm AaBb12
\rmoustache \rmoustache
\root Not supported
\rotatebox Not supported Issue #681
\rparen )\rparen
\rq \rq
\rrbracket \rrbracket
\Rrightarrow \Rrightarrow
\Rsh \Rsh
\rtimes \rtimes
\Rule Not supported see \rule
\rule xxx\rule[6pt]{2ex}{1ex}x x\rule[6pt]{2ex}{1ex}x
\rVert \rVert
\rvert \rvert

S

Symbol/Function Rendered Source or Comment
\S §\text{\S} \text{\S}
\Sampi Not supported
\sampi Not supported
\sc Not supported Issue #471
\scalebox Not supported
\scr Not supported See \mathscr
\scriptscriptstyle cd\scriptscriptstyle \frac cd \scriptscriptstyle \frac cd
\scriptsize scriptsize\scriptsize scriptsize \scriptsize scriptsize
\scriptstyle ab+cd\frac ab + {\scriptstyle \frac cd} \frac ab + {\scriptstyle \frac cd}
\sdot \sdot
\searrow \searrow
\sec sec\sec
\sect §\text{\sect} \text{\sect}
\setlength Not supported Issue #687
\setminus \setminus
\sf AaBb123\sf AaBb123 \sf AaBb123
\sharp \sharp
\shortmid \shortmid
\shortparallel \shortparallel
\shoveleft Not supported
\shoveright Not supported
\sideset Not supported
\Sigma Σ\Sigma
\sigma σ\sigma
\sim \sim
\simeq \simeq
\sin sin\sin
\sinh sinh\sinh
\sixptsize sixptsize\sixptsize sixptsize \sixptsize sixptsize
\sh sh\sh
\skew Not supported
\skip Not supported
\sl Not supported
\small small\small small \small small
\smallfrown \smallfrown
\smallint \smallint
abcd\begin{smallmatrix} a & b \\ c & d \end{smallmatrix} \begin{smallmatrix}
   a & b \\
   c & d
\end{smallmatrix}
\smallsetminus \smallsetminus
\smallsmile \smallsmile
\smash (x2)\left(x^{\smash{2}}\right) \left(x^{\smash{2}}\right)
\smile \smile
\smiley Not supported
\sout abc\sout{abc} \sout{abc}
\Space Not supported see \space
\space a ba\space b a\space b
\spades \spades
\spadesuit \spadesuit
\sphericalangle \sphericalangle
Not supported Issue #1345
\sqcap \sqcap
\sqcup \sqcup
\square \square
\sqrt x3\sqrt[3]{x} \sqrt[3]{x}
\sqsubset \sqsubset
\sqsubseteq \sqsubseteq
\sqsupset \sqsupset
\sqsupseteq \sqsupseteq
\ss ß\text{\ss} \text{\ss}
\stackrel =!\stackrel{!}{=} \stackrel{!}{=}
\star \star
\Stigma Not supported
\stigma Not supported
\strut Not supported
\style Not supported Non standard
\sub \sub
Not supported
\sube \sube
\Subset \Subset
\subset \subset
\subseteq \subseteq
\subseteqq \subseteqq
\subsetneq \subsetneq
\subsetneqq \subsetneqq
\substack $$\sum_{\substack{0<i<m\0<j<n}}$$ \sum_{\substack{0<i<m\\0<j<n}}
\succ \succ
\succapprox \succapprox
\succcurlyeq \succcurlyeq
\succeq \succeq
\succnapprox \succnapprox
\succneqq \succneqq
\succnsim \succnsim
\succsim \succsim
\sum \sum
\sup sup\sup
\supe \supe
\Supset \Supset
\supset \supset
\supseteq \supseteq
\supseteqq \supseteqq
\supsetneq \supsetneq
\supsetneqq \supsetneqq
\surd \surd
\swarrow \swarrow

T

Symbol/Function Rendered Source or Comment
\tag $$\tag{3.1c} a^2+b^2=c^2$$ \tag{3.1c} a^2+b^2=c^2
\tag* $$\tag*{3.1c} a^2+b^2=c^2$$ \tag*{3.1c} a^2+b^2=c^2
\tan tan\tan
\tanh tanh\tanh
\Tau T\Tau
\tau τ\tau
\tbinom (nk)\tbinom n k \tbinom n k
\TeX TeX\TeX
\text  yes & no \text{ yes }\&\text{ no } \text{ yes }\&\text{ no }
\textasciitilde ~\text{\textasciitilde} \text{\textasciitilde}
\textasciicircum ^\text{\textasciicircum} \text{\textasciicircum}
\textbackslash \\text{\textbackslash} \text{\textbackslash}
\textbar |\text{\textbar} \text{\textbar}
\textbardbl \text{\textbardbl} \text{\textbardbl}
\textbf AaBb123\textbf{AaBb123} \textbf{AaBb123}
\textbraceleft {\text{\textbraceleft} \text{\textbraceleft}
\textbraceright }\text{\textbraceright} \text{\textbraceright}
\textcircled a\text{\textcircled a} \text{\textcircled a}
\textcolor F=ma\textcolor{blue}{F=ma} \textcolor{blue}{F=ma}
\textdagger \text{\textdagger} \text{\textdagger}
\textdaggerdbl \text{\textdaggerdbl} \text{\textdaggerdbl}
\textdegree °\text{\textdegree} \text{\textdegree}
\textdollar $\text{\textdollar} \text{\textdollar}
\textellipsis \text{\textellipsis} \text{\textellipsis}
\textemdash \text{\textemdash} \text{\textemdash}
\textendash \text{\textendash} \text{\textendash}
\textgreater >\text{\textgreater} \text{\textgreater}
\textit AaBb\textit{AaBb} \textit{AaBb}
\textless <\text{\textless} \text{\textless}
\textmd AaBb123\textmd{AaBb123} \textmd{AaBb123}
\textnormal AB\textnormal{AB} \textnormal{AB}
\textquotedblleft \text{\textquotedblleft} \text{\textquotedblleft}
\textquotedblright \text{\textquotedblright} \text{\textquotedblright}
\textquoteleft \text{\textquoteleft} \text{\textquoteleft}
\textquoteright \text{\textquoteright} \text{\textquoteright}
\textregistered ®\text{\textregistered} \text{\textregistered}
\textrm AaBb123\textrm{AaBb123} \textrm{AaBb123}
\textsc Not supported Issue #471
\textsf AaBb123\textsf{AaBb123} \textsf{AaBb123}
\textsl Not supported
\textsterling £\text{\textsterling} \text{\textsterling}
\textstyle 0n\textstyle\sum_0^n \textstyle\sum_0^n
\texttip Not supported
\texttt AaBb123\texttt{AaBb123} \texttt{AaBb123}
\textunderscore _\text{\textunderscore} \text{\textunderscore}
\textup AaBb123\textup{AaBb123} \textup{AaBb123}
\textvisiblespace Not supported
\tfrac ab\tfrac ab \tfrac ab
\tg tg\tg
\th th\th
\therefore \therefore
\Theta Θ\Theta
\theta θ\theta
\thetasym ϑ\thetasym
\thickapprox \thickapprox
\thicksim \thicksim
\thickspace a  ba\thickspace b a\thickspace b
\thinspace aba\thinspace b a\thinspace b
\tilde M~\tilde M \tilde M
\times ×\times
\Tiny Not supported see \tiny
\tiny tiny\tiny tiny \tiny tiny
\to \to
\toggle Not supported
\top \top
\triangle \triangle
\triangledown \triangledown
\triangleleft \triangleleft
\trianglelefteq \trianglelefteq
\triangleq \triangleq
\triangleright \triangleright
\trianglerighteq \trianglerighteq
\tt AaBb123{\tt AaBb123} {\tt AaBb123}
\twoheadleftarrow \twoheadleftarrow
\twoheadrightarrow \twoheadrightarrow

U

Symbol/Function Rendered Source or Comment
\u a˘\text{\u{a}} \text{\u{a}}
\Uarr \Uarr
\uArr \uArr
\uarr \uarr
\ulcorner \ulcorner
\underbrace x++xn times\underbrace{x+⋯+x}_{n\text{ times}} \underbrace{x+⋯+x}_{n\text{ times}}
\underbracket Not supported
\undergroup AB\undergroup{AB} \undergroup{AB}
\underleftarrow AB\underleftarrow{AB} \underleftarrow{AB}
\underleftrightarrow AB\underleftrightarrow{AB} \underleftrightarrow{AB}
\underrightarrow AB\underrightarrow{AB} \underrightarrow{AB}
\underline a long argument\underline{\text{a long argument}} \underline{\text{a long argument}}
\underlinesegment ABundefined\underlinesegment{AB} \underlinesegment{AB}
\underparen Not supported See \undergroup
\underrightarrow AB\underrightarrow{AB} \underrightarrow{AB}
\underset =!\underset{!}{=} \underset{!}{=}
\unicode Not supported
\unlhd \unlhd
\unrhd \unrhd
\up Not supported
\Uparrow \Uparrow
\uparrow \uparrow
\Updownarrow \Updownarrow
\updownarrow \updownarrow
\upharpoonleft \upharpoonleft
\upharpoonright \upharpoonright
\uplus \uplus
\uproot Not supported
\upshape Not supported
\Upsilon Υ\Upsilon
\upsilon υ\upsilon
\upuparrows \upuparrows
\urcorner \urcorner
\url \url\footnotesize\url{https://katex.org/} \url{https://katex.org/} Requires trust
\utilde AB~\utilde{AB} \utilde{AB}

V

Symbol/Function Rendered Source or Comment
\v aˇ\text{\v{a}} \text{\v{a}}
\varcoppa Not supported
\varDelta Δ\varDelta
\varepsilon ε\varepsilon
\varGamma Γ\varGamma
\varinjlim Not supported
\varkappa ϰ\varkappa
\varLambda Λ\varLambda
\varliminf Not supported
\varlimsup Not supported
\varnothing \varnothing
\varOmega Ω\varOmega
\varPhi Φ\varPhi
\varphi φ\varphi
\varPi Π\varPi
\varpi ϖ\varpi
\varprojlim Not supported
\varpropto \varpropto
\varPsi Ψ\varPsi
\varPsi Ψ\varPsi
\varrho ϱ\varrho
\varSigma Σ\varSigma
\varsigma ς\varsigma
\varstigma Not supported
\varsubsetneq \varsubsetneq
\varsubsetneqq \varsubsetneqq
\varsupsetneq \varsupsetneq
\varsupsetneqq \varsupsetneqq
\varTheta Θ\varTheta
\vartheta ϑ\vartheta
\vartriangle \vartriangle
\vartriangleleft \vartriangleleft
\vartriangleright \vartriangleright
\varUpsilon Υ\varUpsilon
\varXi Ξ\varXi
\vcentcolon :\vcentcolon
\vcenter Not supported
\Vdash \Vdash
\vDash \vDash
\vdash \vdash
\vdots \vdots
\vec F\vec{F} \vec{F}
\vee \vee
\veebar \veebar
\verb \frac a b\verb!\frac a b! \verb!\frac a b!
\Vert \Vert
\vert \vert
\vfil Not supported
\vfill Not supported
\vline Not supported Issue #269
abcd\begin{Vmatrix}a&b\\c&d\end{Vmatrix} \begin{Vmatrix}
   a & b \\
   c & d
\end{Vmatrix}
abcd\begin{vmatrix}a&b\\c&d\end{vmatrix} \begin{vmatrix}
   a & b \\
   c & d
\end{vmatrix}
\vphantom Ma\overline{\vphantom{M}a} \overline{\vphantom{M}a}
\Vvdash \Vvdash

W

Symbol/Function Rendered Source or Comment
\wedge \wedge
\weierp \weierp
\widecheck ABˇ\widecheck{AB} \widecheck{AB}
\widehat AB^\widehat{AB} \widehat{AB}
\wideparen Not supported Issue #560
\widetilde AB~\widetilde{AB} \widetilde{AB}
\wp \wp
\wr \wr

X

Symbol/Function Rendered Source or Comment
\xcancel ABC\xcancel{ABC} \xcancel{ABC}
\xdef a\def\foo{a}\xdef\bar{\foo}\def\foo{}\bar \def\foo{a}\xdef\bar{\foo}\def\foo{}\bar
\Xi Ξ\Xi
\xi ξ\xi
\xhookleftarrow abc\xhookleftarrow{abc} \xhookleftarrow{abc}
\xhookrightarrow abc\xhookrightarrow{abc} \xhookrightarrow{abc}
\xLeftarrow abc\xLeftarrow{abc} \xLeftarrow{abc}
\xleftarrow abc\xleftarrow{abc} \xleftarrow{abc}
\xleftharpoondown abc\xleftharpoondown{abc} \xleftharpoondown{abc}
\xleftharpoonup abc\xleftharpoonup{abc} \xleftharpoonup{abc}
\xLeftrightarrow abc\xLeftrightarrow{abc} \xLeftrightarrow{abc}
\xleftrightarrow abc\xleftrightarrow{abc} \xleftrightarrow{abc}
\xleftrightharpoons abc\xleftrightharpoons{abc} \xleftrightharpoons{abc}
\xlongequal =abc\xlongequal{abc} \xlongequal{abc}
\xmapsto abc\xmapsto{abc} \xmapsto{abc}
\xRightarrow abc\xRightarrow{abc} \xRightarrow{abc}
\xrightarrow abc\xrightarrow{abc} \xrightarrow{abc}
\xrightharpoondown abc\xrightharpoondown{abc} \xrightharpoondown{abc}
\xrightharpoonup abc\xrightharpoonup{abc} \xrightharpoonup{abc}
\xrightleftharpoons abc\xrightleftharpoons{abc} \xrightleftharpoons{abc}
\xtofrom abc\xtofrom{abc} \xtofrom{abc}
\xtwoheadleftarrow abc\xtwoheadleftarrow{abc} \xtwoheadleftarrow{abc}
\xtwoheadrightarrow abc\xtwoheadrightarrow{abc} \xtwoheadrightarrow{abc}

YZ

Symbol/Function Rendered Source or Comment
\yen ¥\yen
\Z Z\Z
\Zeta Z\Zeta
\zeta ζ\zeta
]]>
KaTeX: Support table

note

This is an direct shameful copy of the documentation pulled from KaTeX documentation, I do not own any of the content below on behalf of this part of the documentation, the table might be outdated as versions migrates, please also refer to KaTeX's official documentation.

Symbols

Symbol/Function Rendered Source or Comment
! n!n! n!
\! a ⁣ba\!b a\!b
# y2\def\bar#1{#1^2} \bar{y} \def\bar#1{#1^2} \bar{y}
\# #\#
% %this is a comment
\% %\%
& abcd\begin{matrix} a & b\cr c & d \end{matrix} \begin{matrix}
   a & b \\
   c & d
\end{matrix}
\& &\&
' '
\' aˊ\text{\'{a}} \text{\'{a}}
( ((
) ))
\(…\) ab\text{\(\frac a b\)} \text{\(\frac a b\)}
\ a ba\ b a\ b
\" a¨\text{\"{a}} \text{\"{a}}
\$ $\text{\textdollar}
\, aba\,\,{b} a\,\,{b}
\. a˙\text{\.{a}} \text{\.{a}}
\: aba\:\:{b} a\:\:{b}
\; a    ba\;\;{b} a\;\;{b}
_ xix_i x_i
\_ _\_
\` aˋ\text{\`{a}} \text{\'{a}}
< <<
\= aˉ\text{\={a}} \text{\\={a}}
> >>
\> aba\>\>{b} a\>\>{b}
[ [[
] ]]
{ a{a} {a}
} a{a} {a}
\{ {\{
\} }\}
| \vert
\| \Vert
~ no no no breaks\text{no~no~no~breaks} \text{no~no~no~breaks}
\~ a˜\text{\~{a}} \text{\\~{a}}
\\ abcd\begin{matrix} a & b\\ c & d\end{matrix} \begin{matrix}
   a & b \\
   c & d
\end{matrix}
^ xix^i x^i
\^ aˆ\text{\^{a}} \text{\\^{a}}

A

Symbol/Function Rendered Source or Comment
\AA A˚\text{\AA} \text{\AA}
\aa a˚\text{\aa} \text{\aa}
\above ab+1{a \above{2pt} b+1} {a \above{2pt} b+1}
\abovewithdelims Not supported
\acute eˊ\acute e \acute e
\AE Æ\text{\AE} \text{\AE}
\ae æ\text{\ae} \text{\ae}
\alef \alef
\alefsym \alefsym
\aleph \aleph
Not supported see {aligned}
a=b+cd+e=f\begin{aligned}a&=b+c\\d+e&=f\end{aligned} \begin{aligned}
   a&=b+c \\
   d+e&=f
\end{aligned}
Not supported see {alignedat}
10x+3y=23x+13y=4\begin{alignedat}{2}10&x+&3&y=2\\3&x+&13&y=4\end{alignedat} \begin{alignedat}{2}
   10&x+ &3&y = 2 \\
    3&x+&13&y = 4
\end{alignedat}
\allowbreak
\Alpha A\Alpha
\alpha α\alpha
\amalg ⨿\amalg
\And &\And
\and Not supported Deprecated
\ang Not supported Deprecated
\angl Not supported
\angle \angle
\approx \approx
\approxeq \approxeq
\arccos arccos\arccos
\arcctg arcctg\arcctg
\arcsin arcsin\arcsin
\arctan arctan\arctan
\arctg arctg\arctg
\arg arg\arg
\argmax arg max\argmax
\argmin arg min\argmin
abcd\begin{array}{cc}a&b\\c&d\end{array} \begin{array}{cc}
   a & b \\
   c & d
\end{array}
\array Not supported see {array}
\arraystretch abcd\def\arraystretch{1.5}\begin{array}{cc}a&b\\c&d\end{array} \def\arraystretch{1.5}
\begin{array}{cc}
   a & b \\
   c & d
\end{array}
\Arrowvert Not supported
\arrowvert Not supported
\ast \ast
\asymp \asymp
\atop ab{a \atop b} {a \atop b}
\atopwithdelims Not supported

B

| Symbol/Function | Rendered | Source or Comment | | :------------------ | :-------------------------------------------------- | :------------------------------------------------------------------------------------------------ | ------ | | \backepsilon | \backepsilon | | | \backprime | \backprime | | | \backsim | \backsim | | | \backsimeq | \backsimeq | | | \backslash | \\backslash | | | \bar | yˉ\bar{y} | \bar{y} | | \barwedge | \barwedge | | | \Bbb | ABC\Bbb{ABC} | \Bbb{ABC}
KaTeX supports A-Z & k | | \Bbbk | k\Bbbk | | | \bbox | Not supported | | | \bcancel | 5\bcancel{5} | \bcancel{5} | | \because | \because | | | \begin | abcd\begin{matrix} a & b\\ c & d\end{matrix} | \begin{matrix}
   a & b \\
   c & d
\end{matrix} | | \begingroup | \begingroup a} | \begingroup a} | | \Beta | B\Beta | | | \beta | β\beta | | | \beth | \beth | | | \between | \between | | | \bf | AaBb12\bf AaBb12 | \bf AaBb12 | | \bfseries | Not supported | | | \big | ()\big(\big) | \big(\big) | | \Big | ()\Big(\Big) | \Big(\Big) | | \bigcap | \bigcap | | | \bigcirc | \bigcirc | | | \bigcup | \bigcup | | | \bigg | ()\bigg(\bigg) | \bigg(\bigg) | | \Bigg | ()\Bigg(\Bigg) | \Bigg(\Bigg) | | \biggl | (\biggl( | \biggl( | | \Biggl | (\Biggl( | \Biggl( | | \biggm | \biggm\vert | \biggm\vert | | \Biggm | \Biggm\vert | \Biggm\vert | | \biggr | )\biggr) | \biggr) | | \Biggr | )\Biggr) | \Biggr) | | \bigl | (\bigl( | \bigl( | | \Bigl | (\Bigl( | \Bigl( | | \bigm | \bigm\vert | \bigm\vert | | \Bigm | \Bigm\vert | \Bigm\vert | | \bigodot | \bigodot | | | \bigominus | Not supported | Issue #1222 | | \bigoplus | \bigoplus | | | \bigoslash | Not supported | Issue #1222 | | \bigotimes | \bigotimes | | | \bigr | )\bigr) | \bigr) | | \Bigr | )\Bigr) | \Bigr) | | \bigsqcap | Not supported | Issue #1222 | | \bigsqcup | \bigsqcup | | | \bigstar | \bigstar | | | \bigtriangledown | \bigtriangledown | | | \bigtriangleup | \bigtriangleup | | | \biguplus | \biguplus | | | \bigvee | \bigvee | | | \bigwedge | \bigwedge | | | \binom | (nk)\binom n k | \binom n k | | \blacklozenge | \blacklozenge | | | \blacksquare | \blacksquare | | | \blacktriangle | \blacktriangle | | | \blacktriangledown | \blacktriangledown | | | \blacktriangleleft | \blacktriangleleft | | | \blacktriangleright | \blacktriangleright | | | \bm | AaBb\bm{AaBb} | \bm{AaBb} | | {Bmatrix} | {abcd}\begin{Bmatrix}a&b\\c&d\end{Bmatrix} | \begin{Bmatrix}
   a & b \\
   c & d
\end{Bmatrix} | | {bmatrix} | [abcd]\begin{bmatrix}a&b\\c&d\end{bmatrix} | \begin{bmatrix}
   a & b \\
   c & d
\end{bmatrix} | | \bmod | amodba \bmod b | a \bmod b | | \bold | AaBb123\bold{AaBb123} | \bold{AaBb123} | | \boldsymbol | AaBb\boldsymbol{AaBb} | \boldsymbol{AaBb} | | \bot | \bot | | | \bowtie | \bowtie | | | \Box | \Box | | | \boxdot | \boxdot | | | \boxed | ab\boxed{ab} | \boxed{ab} | | \boxminus | \boxminus | | | \boxplus | \boxplus | | | \boxtimes | \boxtimes | | | \Bra | ψ\left\langle\psi\right\| | \Bra{\psi} | | \bra | ψ\mathinner{\langle{\psi}\|} | \bra{\psi} | | \braket | ϕψ\mathinner{\langle{\phi\|\psi}\rangle} | \braket{\phi | \psi} | | \brace | {nk}{n\brace k} | {n\brace k} | | \bracevert | Not supported | | | \brack | [nk]{n\brack k} | {n\brack k} | | \breve | eu˘\breve{eu} | \breve{eu} | | \buildrel | Not supported | | | \bull | \bull | | | \bullet | \bullet | | | \Bumpeq | \Bumpeq | | | \bumpeq | \bumpeq | |

C

Symbol/Function Rendered Source or Comment
\C Not supported Deprecated
\cal AaBb123\cal AaBb123 \cal AaBb123
\cancel 5\cancel{5} \cancel{5}
\cancelto Not supported
\Cap \Cap
\cap \cap
{aif bcif d\begin{cases}a&\text{if }b\\c&\text{if }d\end{cases} \begin{cases}
   a &\text{if } b \\
   c &\text{if } d
\end{cases}
\cases Not supported see {cases}
Not supported
\cdot \cdot
\cdotp \cdotp
\cdots \cdots
\ce CX6HX5CHO{\mathrm{C}{\vphantom{X}}_{\smash[t]{6}}\mathrm{H}{\vphantom{X}}_{\smash[t]{5}}{-}\mathrm{CHO}}
\ce{C6H5-CHO}
{\mathrm{C}{\vphantom{X}}_{\smash[t]{6}}\mathrm{H}{\vphantom{X}}_{\smash[t]{5}}{-}\mathrm{CHO}}
or \ce{C6H5-CHO} Requires an extension
\cee Not supported Deprecated by mhchem
\centerdot aba\centerdot b a\centerdot b
\cf Not supported Deprecated by mhchem;
use \ce instead
\cfrac 21+21+21\cfrac{2}{1+\cfrac{2}{1+\cfrac{2}{1}}} \cfrac{2}{1+\cfrac{2}{1+\cfrac{2}{1}}}
\check oeˇ\check{oe} \check{oe}
\ch ch\ch
\checkmark \checkmark
\Chi X\Chi
\chi χ\chi
\choose (n+1k+2){n+1 \choose k+2} {n+1 \choose k+2}
\circ \circ
\circeq \circeq
\circlearrowleft \circlearrowleft
\circlearrowright \circlearrowright
\circledast \circledast
\circledcirc \circledcirc
\circleddash \circleddash
\circledR ®\circledR
\circledS \circledS
\class Not supported A PR is pending.
\cline Not supported Issue #269
\clubs \clubs
\clubsuit \clubsuit
\cnums C\cnums
\colon  ⁣:\colon
\Colonapprox \Colonapprox
\colonapprox :\colonapprox
\Coloneq \Coloneq
\coloneq :\coloneq
\Coloneqq =\Coloneqq
\coloneqq \coloneqq
\Colonsim \Colonsim
\colonsim :\colonsim
\color AaBb123\color{#0000FF} AaBb123 \color{#0000FF} AaBb123
\colorbox Black on red\colorbox{red}{Black on red} \colorbox{red}{Black on red}
\complement \complement
\Complex C\Complex
\cong \cong
\Coppa Not supported
\coppa Not supported
\coprod \coprod
\copyright ©\copyright
\cos cos\cos
\cosec cosec\cosec
\cosh cosh\cosh
\cot cot\cot
\cotg cotg\cotg
\coth coth\coth
\cr abcd\begin{matrix} a & b\cr c & d \end{matrix} \begin{matrix}
   a & b \cr
   c & d
\end{matrix}
\csc csc\csc
\cssId Not supported A PR is pending.
\ctg ctg\ctg
\cth cth\cth
\Cup \Cup
\cup \cup
\curlyeqprec \curlyeqprec
\curlyeqsucc \curlyeqsucc
\curlyvee \curlyvee
\curlywedge \curlywedge
\curvearrowleft \curvearrowleft
\curvearrowright \curvearrowright

D

Symbol/Function Rendered Source or Comment
\dag \dag
\Dagger \Dagger
\dagger \dagger
\daleth \daleth
\Darr \Darr
\dArr \dArr
\darr \darr
abcd\begin{darray}{cc}a&b\\c&d\end{darray} \begin{darray}{cc}
   a & b \\
   c & d
\end{darray}
\dashleftarrow \dashleftarrow
\dashrightarrow \dashrightarrow
\dashv \dashv
\dbinom (nk)\dbinom n k \dbinom n k
\dblcolon \dblcolon
{aif bcif d\begin{dcases}a&\text{if }b\\c&\text{if }d\end{dcases} \begin{dcases}
   a &\text{if } b \\
   c &\text{if } d
\end{dcases}
\ddag \ddag
\ddagger \ddagger
\ddddot Not supported
\dddot Not supported
\ddot x¨\ddot x \ddot x
\ddots \ddots
\DeclareMathOperator Not supported
\def x2+x2\def\foo{x^2} \foo + \foo \def\foo{x^2} \foo + \foo
\definecolor Not supported Issue #750
\deg deg\deg
\degree °\degree
\delta δ\delta
\Delta Δ\Delta
\det det\det
\Digamma Not supported
\digamma ϝ\digamma
\dfrac a1b1\dfrac{a-1}{b-1} \dfrac{a-1}{b-1}
\diagdown \diagdown
\diagup \diagup
\Diamond \Diamond
\diamond \diamond
\diamonds \diamonds
\diamondsuit \diamondsuit
\dim dim\dim
\displaylines Not supported
\displaystyle 0n\displaystyle\sum_0^n \displaystyle\sum_0^n
\div ÷\div
\divideontimes \divideontimes
\dot x˙\dot x \dot x
\Doteq \Doteq
\doteq \doteq
\doteqdot \doteqdot
\dotplus \dotplus
\dots x1++xnx_1 + \dots + x_n x_1 + \dots + x_n
\dotsb x1++xnx_1 +\dotsb + x_n x_1 +\dotsb + x_n
\dotsc x,,yx,\dotsc,y x,\dotsc,y
\dotsi $$\int_{A_1}\int_{A_2}\dotsi$$ \int_{A_1}\int_{A_2}\dotsi
\dotsm x1x2xnx_1 x_2 \dotsm x_n $x_1 x_2 \dotsm x_n
\dotso \dotso
\doublebarwedge \doublebarwedge
\doublecap \doublecap
\doublecup \doublecup
\Downarrow \Downarrow
\downarrow \downarrow
\downdownarrows \downdownarrows
\downharpoonleft \downharpoonleft
\downharpoonright \downharpoonright
aif bcif d}\begin{drcases}a&\text{if }b\\c&\text{if }d\end{drcases} \begin{drcases}
   a &\text{if } b \\
   c &\text{if } d
\end{drcases}

E

Symbol/Function Rendered Source or Comment
\edef a\def\foo{a}\edef\bar{\foo}\def\foo{}\bar \def\foo{a}\edef\bar{\foo}\def\foo{}\bar
\ell \ell
\else Not supported Issue #1003
\em Not supported
\emph Not supported
\empty \empty
\emptyset \emptyset
\enclose Not supported Non standard
\end abcd\begin{matrix} a & b\\ c & d\end{matrix} \begin{matrix}
   a & b \\
   c & d
\end{matrix}
\endgroup {a\endgroup {a\endgroup
\enspace aba\enspace b a\enspace b
\Epsilon E\Epsilon
\epsilon ϵ\epsilon
\eqalign Not supported
\eqalignno Not supported
\eqcirc \eqcirc
\Eqcolon \Eqcolon
\eqcolon \eqcolon
Not supported Issue #445
Not supported
\Eqqcolon =\Eqqcolon
\eqqcolon \eqqcolon
\eqref Not supported Issue #350
\eqsim \eqsim
\eqslantgtr \eqslantgtr
\eqslantless \eqslantless
\equiv \equiv
\Eta H\Eta
\eta η\eta
\eth ð\eth
\euro Not supported
\exist \exist
\exists \exists
\exp exp\exp
\expandafter

F

Symbol/Function Rendered Source or Comment
\fallingdotseq \fallingdotseq
\fbox Hi there!\fbox{Hi there!} \fbox{Hi there!}
\fcolorbox A\fcolorbox{red}{aqua}{A} \fcolorbox{red}{aqua}{A}
\fi Not supported Issue #1003
\Finv \Finv
\flat \flat
\footnotesize footnotesize\footnotesize footnotesize \footnotesize footnotesize
\forall \forall
\frac ab\frac a b \frac a b
\frak AaBb\frak{AaBb} \frak{AaBb}
\frown \frown
\futurelet

G

Symbol/Function Rendered Source or Comment
\Game \Game
\Gamma Γ\Gamma
\gamma γ\gamma
Not supported see {gathered}
a=be=b+c\begin{gathered}a=b\\e=b+c\end{gathered} \begin{gathered}
   a=b \\
   e=b+c
\end{gathered}
\gcd gcd\gcd
\gdef y2+y2\gdef\bar#1{#1^2} \bar{y} + \bar{y} \gdef\bar#1{#1^2} \bar{y} + \bar{y}
\ge \ge
\geneuro Not supported
\geneuronarrow Not supported
\geneurowide Not supported
\genfrac (aa+1]\genfrac ( ] {2pt}{0}a{a+1} \genfrac ( ] {2pt}{0}a{a+1}
\geq \geq
\geqq \geqq
\geqslant \geqslant
\gets \gets
\gg \gg
\ggg \ggg
\gggtr \gggtr
\gimel \gimel
\global 2+3\global\def\add#1#2{#1+#2} \add 2 3 \global\def\add#1#2{#1+#2} \add 2 3
\gnapprox \gnapprox
\gneq \gneq
\gneqq \gneqq
\gnsim \gnsim
\grave euˋ\grave{eu} \grave{eu}
\gt a>ba \gt b a \gt b
\gtrdot \gtrdot
\gtrapprox \gtrapprox
\gtreqless \gtreqless
\gtreqqless \gtreqqless
\gtrless \gtrless
\gtrsim \gtrsim
\gvertneqq \gvertneqq

H

Symbol/Function Rendered Source or Comment
\H a˝\text{\H{a}} \text{\H{a}}
\Harr \Harr
\hArr \hArr
\harr \harr
\hat θ^\hat{\theta} \hat{\theta}
\hbar \hbar
\hbox Not supported
\hdashline abcd\begin{matrix}a&b\\ \hdashline c &d\end{matrix} \begin{matrix}
   a & b \\
   \hdashline
   c & d
\end{matrix}
\hearts \hearts
\heartsuit \heartsuit
\hfil Not supported
\hfill Not supported Issues #164 & #269
\hline abcd\begin{matrix}a&b\\ \hline c &d\end{matrix} \begin{matrix}
   a & b \\ \hline
   c & d
\end{matrix}
\hom hom\hom
\hookleftarrow \hookleftarrow
\hookrightarrow \hookrightarrow
\hphantom abcda\hphantom{bc}d a\hphantom{bc}d
\href \href\href{https://katex.org/}{\KaTeX} \href{https://katex.org/}{\KaTeX} Requires trust
\hskip widw\hskip1em i\hskip2em d w\hskip1em i\hskip2em d
\hslash \hslash
\hspace s\hspace7ex k s\hspace7ex k
\htmlClass \htmlClass\htmlClass{foo}{x} \htmlClass{foo}{x} Must enable trust and disable strict
\htmlData \htmlData\htmlData{foo=a, bar=b}{x} \htmlData{foo=a, bar=b}{x} Must enable trust and disable strict
\htmlId \htmlId\htmlId{bar}{x} \htmlId{bar}{x} Must enable trust and disable strict
\htmlStyle \htmlStyle\htmlStyle{color: red;}{x} \htmlStyle{color: red;}{x} Must enable trust and disable strict
\huge huge\huge huge \huge huge
\Huge Huge\Huge Huge \Huge Huge

I

Symbol/Function Rendered Source or Comment
\i ı\text{\i} \text{\i}
\idotsint Not supported
\iddots Not supported Issue #1223
\if Not supported Issue #1003
\iff A    BA\iff B A\iff B
\ifmode Not supported Issue #1003
\ifx Not supported Issue #1003
\iiiint Not supported
\iiint \iiint
\iint \iint
\Im \Im
\image \image
\imath ı\imath
\impliedby P    QP\impliedby Q P\impliedby Q
\implies P    QP\implies Q P\implies Q
\in \in
\includegraphics \includegraphics\includegraphics[height=0.8em, totalheight=0.9em, width=0.9em, alt=KA logo]{https://cdn.kastatic.org/images/apple-touch-icon-57x57-precomposed.new.png} \includegraphics[height=0.8em, totalheight=0.9em, width=0.9em, alt=KA logo]{https://cdn.kastatic.org/images/apple-touch-icon-57x57-precomposed.new.png} Requires trust
\inf inf\inf
\infin \infin
\infty \infty
\injlim Not supported
\int \int
\intercal \intercal
\intop \intop
\Iota I\Iota
\iota ι\iota
\isin \isin
\it AaBb{\it AaBb} {\it AaBb}
\itshape Not supported

JK

Symbol/Function Rendered Source or Comment
\j ȷ\text{\j} \text{\j}
\jmath ȷ\jmath
\Join \Join
\Kappa K\Kappa
\kappa κ\kappa
\KaTeX KaTeX\KaTeX
\ker ker\ker
\kern IRI\kern-2.5pt R I\kern-2.5pt R
\Ket ψ\left|\psi\right\rangle \Ket{\psi}
\ket ψ\mathinner{|{\psi}\rangle} \ket{\psi}
\Koppa Not supported
\koppa Not supported

L

Symbol/Function Rendered Source or Comment
\L Not supported
\l Not supported
\Lambda Λ\Lambda
\lambda λ\lambda
\label Not supported
\land \land
\lang A\lang A\rangle \lang A\rangle
\langle A\langle A\rangle \langle A\rangle
\Larr \Larr
\lArr \lArr
\larr \larr
\large large\large large \large large
\Large Large\Large Large \Large Large
\LARGE LARGE\LARGE LARGE \LARGE LARGE
\LaTeX LaTeX\LaTeX
\lBrace \lBrace
\lbrace {\lbrace
\lbrack [\lbrack
\lceil \lceil
\ldotp .\ldotp
\ldots \ldots
\le \le
\leadsto \leadsto
\left {ab\left\lbrace \dfrac ab \right. \left\lbrace \dfrac ab \right.
\leftarrow \leftarrow
\Leftarrow \Leftarrow
\LeftArrow Not supported Non standard
\leftarrowtail Not supported
\leftharpoondown \leftharpoondown
\leftharpoonup \leftharpoonup
\leftleftarrows \leftleftarrows
\Leftrightarrow \Leftrightarrow
\leftrightarrow \leftrightarrow
\leftrightarrows \leftrightarrows
\leftrightharpoons \leftrightharpoons
\leftrightsquigarrow \leftrightsquigarrow
\leftroot Not supported
\leftthreetimes \leftthreetimes
\leq \leq
\leqalignno Not supported
\leqq \leqq
\leqslant \leqslant
\lessapprox \lessapprox
\lessdot \lessdot
\lesseqgtr \lesseqgtr
\lesseqqgtr \lesseqqgtr
\lessgtr \lessgtr
\lesssim \lesssim
\let
\lfloor \lfloor
\lg lg\lg
\lgroup \lgroup
\lhd \lhd
\lim lim\lim
\liminf lim inf\liminf
\limits limx\lim\limits_x \lim\limits_x
\limsup lim sup\limsup
\ll \ll
\llap =/{=}\llap{/\,} {=}\llap{/\,}
\llbracket \llbracket
\llcorner \llcorner
\Lleftarrow \Lleftarrow
\lll \lll
\llless \llless
\lmoustache \lmoustache
\ln ln\ln
\lnapprox \lnapprox
\lneq \lneq
\lneqq \lneqq
\lnot ¬\lnot
\lnsim \lnsim
\log log\log
\long
\Longleftarrow \Longleftarrow
\longleftarrow \longleftarrow
\Longleftrightarrow \Longleftrightarrow
\longleftrightarrow \longleftrightarrow
\longmapsto \longmapsto
\Longrightarrow \Longrightarrow
\longrightarrow \longrightarrow
\looparrowleft \looparrowleft
\looparrowright \looparrowright
\lor \lor
\lower Not supported
\lozenge \lozenge
\lparen (\lparen
\Lrarr \Lrarr
\lrArr \lrArr
\lrarr \lrarr
\lrcorner \lrcorner
\lq \lq
\Lsh \Lsh
\lt <\lt
\ltimes \ltimes
\lVert \lVert
\lvert \lvert
\lvertneqq \lvertneqq

M

Symbol/Function Rendered Source or Comment
\maltese \maltese
\mapsto \mapsto
\mathbb AB\mathbb{AB} \mathbb{AB}
KaTeX supports A-Z k
\mathbf AaBb123\mathbf{AaBb123} \mathbf{AaBb123}
\mathbin a!ba\mathbin{!}b a\mathbin{!}b
\mathcal AaBb123\mathcal{AaBb123} \mathcal{AaBb123}
\mathchoice aba\mathchoice{\,}{\,\,}{\,\,\,}{\,\,\,\,}b a\mathchoice{\,}{\,\,}{\,\,\,}{\,\,\,\,}b
\mathclap 1inxi\displaystyle\sum_{\mathclap{1\le i\le n}} x_{i} \sum_{\mathclap{1\le i\le n}} x_{i}
\mathclose a+(b>+ca + (b\mathclose\gt + c a + (b\mathclose\gt + c
\mathellipsis \mathellipsis
\mathfrak AaBb\mathfrak{AaBb} \mathfrak{AaBb}
KaTeX supports A-Za-z
\mathinner abinsidecdab\mathinner{\text{inside}}cd ab\mathinner{\text{inside}}cd
\mathit AaBb\mathit{AaBb} \mathit{AaBb}
KaTeX supports A-Za-z
\mathllap =/{=}\mathllap{/\,} {=}\mathllap{/\,}
\mathnormal AaBb\mathnormal{AaBb} \mathnormal{AaBb}
KaTeX supports A-Za-z
\mathop ab\mathop{\star}_a^b \mathop{\star}_a^b
\mathopen a+<b)+ca + \mathopen\lt b) + c a + \mathopen\lt b) + c
\mathord 1,234,5671\mathord{,}234{,}567 1\mathord{,}234{,}567
\mathpunct ABA\mathpunct{-}B A\mathpunct{-}B
\mathrel a#ba \mathrel{\#} b a \mathrel{\#} b
\mathrlap /=\mathrlap{\,/}{=} \mathrlap{\,/}{=}
\mathring a˚\mathring{a} \mathring{a}
\mathrm AaBb123\mathrm{AaBb123} \mathrm{AaBb123}
\mathscr AB\mathscr{AB} \mathscr{AaBb123}
KaTeX supports A-Z
\mathsf AaBb123\mathsf{AaBb123} \mathsf{AaBb123}
\mathsterling £\mathsterling
\mathstrut Not supported
\mathtip Not supported
\mathtt AaBb123\mathtt{AaBb123} \mathtt{AaBb123}
\matrix Not supported See {matrix}
abcd\begin{matrix}a&b\\c&d\end{matrix} \begin{matrix}
   a & b \\
   c & d
\end{matrix}
\max max\max
\mbox Not supported
\md Not supported
\mdseries Not supported
\measuredangle \measuredangle
\medspace aba\medspace b a\medspace b
\mho \mho
\mid {xRx>0}\{x∈ℝ\mid x>0\} \{x∈ℝ\mid x>0\}
\middle P(A|B)P\left(A\middle\vert B\right) P\left(A\middle\vert B\right)
\min min\min
\mit Not supported See \mathit
\mkern aba\mkern18mu b a\mkern18mu b
\mmlToken Not supported
\mod 35mod23\equiv 5 \mod 2 3\equiv 5 \mod 2
\models \models
\moveleft Not supported
\moveright Not supported
\mp \mp
\mskip aba\mskip{10mu}b a\mskip{10mu}b
\mspace Not supported
\Mu M\Mu
\mu μ\mu
\multicolumn Not supported Issue #269
Not supported
\multimap \multimap

N

Symbol/Function Rendered Source or Comment
\N N\N
\nabla \nabla
\natnums N\natnums
\natural \natural
\negmedspace a ⁣ba\negmedspace b a\negmedspace b
\ncong \ncong
\ne \ne
\nearrow \nearrow
\neg ¬\neg
\negthickspace a ⁣ba\negthickspace b a\negthickspace b
\negthinspace a ⁣ba\negthinspace b a\negthinspace b
\neq \neq
\newcommand \newcommand\chk{\checkmark} \chk \newcommand\chk{\checkmark} \chk
\newenvironment Not supported Issue #37
\Newextarrow Not supported
\newline aba\newline b a\newline b
\nexists \nexists
\ngeq \ngeq
\ngeqq \ngeqq
\ngeqslant \ngeqslant
\ngtr \ngtr
\ni \ni
\nleftarrow \nleftarrow
\nLeftarrow \nLeftarrow
\nLeftrightarrow \nLeftrightarrow
\nleftrightarrow \nleftrightarrow
\nleq \nleq
\nleqq \nleqq
\nleqslant \nleqslant
\nless \nless
\nmid \nmid
\nobreak
\nobreakspace a ba\nobreakspace b a\nobreakspace b
\noexpand
\nolimits limx\lim\nolimits_x \lim\nolimits_x
\normalfont Not supported
\normalsize normalsize\normalsize normalsize \normalsize normalsize
\not \not = \not =
\notag Not supported
\notin \notin
\notni \notni
\nparallel \nparallel
\nprec \nprec
\npreceq \npreceq
\nRightarrow \nRightarrow
\nrightarrow \nrightarrow
\nshortmid \nshortmid
\nshortparallel \nshortparallel
\nsim \nsim
\nsubseteq \nsubseteq
\nsubseteqq \nsubseteqq
\nsucc \nsucc
\nsucceq \nsucceq
\nsupseteq \nsupseteq
\nsupseteqq \nsupseteqq
\ntriangleleft \ntriangleleft
\ntrianglelefteq \ntrianglelefteq
\ntriangleright \ntriangleright
\ntrianglerighteq \ntrianglerighteq
\Nu N\Nu
\nu ν\nu
\nVDash \nVDash
\nVdash \nVdash
\nvDash \nvDash
\nvdash \nvdash
\nwarrow \nwarrow

O

Symbol/Function Rendered Source or Comment
\O Ø\text{\O} \text{\O}
\o ø\text{\o} \text{\o}
\odot \odot
\OE Œ\text{\OE} \text{\OE}
\oe œ\text{\oe} \text{\oe}
\officialeuro Not supported
\oiiint \oiiint
\oiint \oiint
\oint \oint
\oldstyle Not supported
\omega ω\omega
\Omega Ω\Omega
\Omicron O\Omicron
\omicron ο\omicron
\ominus \ominus
\operatorname asinx\operatorname{asin} x \operatorname{asin} x
\operatorname* asinyx\operatorname{asin}\limits_y x \operatorname{asin}\limits_y x
\oplus \oplus
\or Not supported
\oslash \oslash
\otimes \otimes
\over a+1b+2+c{a+1 \over b+2}+c {a+1 \over b+2}+c
\overbrace x++xn times\overbrace{x+⋯+x}^{n\text{ times}} \overbrace{x+⋯+x}^{n\text{ times}}
\overbracket Not supported
\overgroup AB\overgroup{AB} \overgroup{AB}
\overleftarrow AB\overleftarrow{AB} \overleftarrow{AB}
\overleftharpoon AB\overleftharpoon{AB} \overleftharpoon{AB}
\overleftrightarrow AB\overleftrightarrow{AB} \overleftrightarrow{AB}
\overline a long argument\overline{\text{a long argument}} \overline{\text{a long argument}}
\overlinesegment ABundefined\overlinesegment{AB} \overlinesegment{AB}
\overparen Not supported See \overgroup
\Overrightarrow AB\Overrightarrow{AB} \Overrightarrow{AB}
\overrightarrow AB\overrightarrow{AB} \overrightarrow{AB}
\overrightharpoon ac\overrightharpoon{ac} \overrightharpoon{ac}
\overset =!\overset{!}{=} \overset{!}{=}
\overwithdelims Not supported
\owns \owns

P

Symbol/Function Rendered Source or Comment
\P \text{\P} \text{\P}
\pagecolor Not supported Deprecated
\parallel \parallel
\part Not supported Deprecated
\partial \partial
\perp \perp
\phantom Γijkij\Gamma^{\phantom{i}j}_{i\phantom{j}k} \Gamma^{\phantom{i}j}_{i\phantom{j}k}
\phase Not supported
\Phi Φ\Phi
\phi ϕ\phi
\Pi Π\Pi
\pi π\pi
Not supported
\pitchfork \pitchfork
\plim plim\plim
\plusmn ±\plusmn
\pm ±\pm
\pmatrix Not supported See {pmatrix}
(abcd)\begin{pmatrix}a&b\\c&d\end{pmatrix} \begin{pmatrix}
   a & b \\
   c & d
\end{pmatrix}
\pmb μ\pmb{\mu} \pmb{\mu}
\pmod x(moda)x\pmod a x\pmod a
\pod x(a)x \pod a x \pod a
\pounds £\pounds
\Pr Pr\Pr
\prec \prec
\precapprox \precapprox
\preccurlyeq \preccurlyeq
\preceq \preceq
\precnapprox \precnapprox
\precneqq \precneqq
\precnsim \precnsim
\precsim \precsim
\prime \prime
\prod \prod
\projlim Not supported
\propto \propto
\providecommand Hello\providecommand\greet{\text{Hello}} \greet \providecommand\greet{\text{Hello}} \greet
\psi ψ\psi
\Psi Ψ\Psi
\pu 123 kJmol{123~\mathchoice{\textstyle\frac{\mathrm{kJ}}{\mathrm{mol}}}{\frac{\mathrm{kJ}}{\mathrm{mol}}}{\frac{\mathrm{kJ}}{\mathrm{mol}}}{\frac{\mathrm{kJ}}{\mathrm{mol}}}} \pu{123 kJ//mol} Requires an extension

QR

Symbol/Function Rendered Source or Comment
\Q Not supported See \Bbb{Q}
\qquad aba\qquad\qquad{b} a\qquad\qquad{b}
\quad aba\quad\quad{b} a\quad\quad{b}
\R R\R
\r a˚\text{\r{a}} \text{\r{a}}
\raise Not supported see \raisebox
\raisebox higherh\raisebox{2pt}{ighe}r h\raisebox{2pt}{ighe}r
\rang A\langle A\rang \langle A\rang
\rangle A\langle A\rangle \langle A\rangle
\Rarr \Rarr
\rArr \rArr
\rarr \rarr
\rBrace \rBrace
\rbrace }\rbrace
\rbrack ]\rbrack
aif bcif d}\begin{rcases}a&\text{if }b\\c&\text{if }d\end{rcases} \begin{rcases}
   a &\text{if } b \\
   c &\text{if } d
\end{rcases}
\rceil \rceil
\Re \Re
\real \real
\Reals R\Reals
\reals R\reals
\ref Not supported Issue #350
\relax
\renewcommand Ahoy!\def\hail{Hi!}\renewcommand\hail{\text{Ahoy!}} \hail \def\hail{Hi!}
\renewcommand\hail{\text{Ahoy!}}
\hail
\renewenvironment Not supported
\require Not supported
\restriction \restriction
\rfloor \rfloor
\rgroup \rgroup
\rhd \rhd
\Rho P\Rho
\rho ρ\rho
\right ab)\left.\dfrac a b\right) \left.\dfrac a b\right)
\Rightarrow \Rightarrow
\rightarrow \rightarrow
\rightarrowtail \rightarrowtail
\rightharpoondown \rightharpoondown
\rightharpoonup \rightharpoonup
\rightleftarrows \rightleftarrows
\rightleftharpoons \rightleftharpoons
\rightrightarrows \rightrightarrows
\rightsquigarrow \rightsquigarrow
\rightthreetimes \rightthreetimes
\risingdotseq \risingdotseq
\rlap /=\rlap{\,/}{=} \rlap{\,/}{=}
\rm AaBb12\rm AaBb12 \rm AaBb12
\rmoustache \rmoustache
\root Not supported
\rotatebox Not supported Issue #681
\rparen )\rparen
\rq \rq
\rrbracket \rrbracket
\Rrightarrow \Rrightarrow
\Rsh \Rsh
\rtimes \rtimes
\Rule Not supported see \rule
\rule xxx\rule[6pt]{2ex}{1ex}x x\rule[6pt]{2ex}{1ex}x
\rVert \rVert
\rvert \rvert

S

Symbol/Function Rendered Source or Comment
\S §\text{\S} \text{\S}
\Sampi Not supported
\sampi Not supported
\sc Not supported Issue #471
\scalebox Not supported
\scr Not supported See \mathscr
\scriptscriptstyle cd\scriptscriptstyle \frac cd \scriptscriptstyle \frac cd
\scriptsize scriptsize\scriptsize scriptsize \scriptsize scriptsize
\scriptstyle ab+cd\frac ab + {\scriptstyle \frac cd} \frac ab + {\scriptstyle \frac cd}
\sdot \sdot
\searrow \searrow
\sec sec\sec
\sect §\text{\sect} \text{\sect}
\setlength Not supported Issue #687
\setminus \setminus
\sf AaBb123\sf AaBb123 \sf AaBb123
\sharp \sharp
\shortmid \shortmid
\shortparallel \shortparallel
\shoveleft Not supported
\shoveright Not supported
\sideset Not supported
\Sigma Σ\Sigma
\sigma σ\sigma
\sim \sim
\simeq \simeq
\sin sin\sin
\sinh sinh\sinh
\sixptsize sixptsize\sixptsize sixptsize \sixptsize sixptsize
\sh sh\sh
\skew Not supported
\skip Not supported
\sl Not supported
\small small\small small \small small
\smallfrown \smallfrown
\smallint \smallint
abcd\begin{smallmatrix} a & b \\ c & d \end{smallmatrix} \begin{smallmatrix}
   a & b \\
   c & d
\end{smallmatrix}
\smallsetminus \smallsetminus
\smallsmile \smallsmile
\smash (x2)\left(x^{\smash{2}}\right) \left(x^{\smash{2}}\right)
\smile \smile
\smiley Not supported
\sout abc\sout{abc} \sout{abc}
\Space Not supported see \space
\space a ba\space b a\space b
\spades \spades
\spadesuit \spadesuit
\sphericalangle \sphericalangle
Not supported Issue #1345
\sqcap \sqcap
\sqcup \sqcup
\square \square
\sqrt x3\sqrt[3]{x} \sqrt[3]{x}
\sqsubset \sqsubset
\sqsubseteq \sqsubseteq
\sqsupset \sqsupset
\sqsupseteq \sqsupseteq
\ss ß\text{\ss} \text{\ss}
\stackrel =!\stackrel{!}{=} \stackrel{!}{=}
\star \star
\Stigma Not supported
\stigma Not supported
\strut Not supported
\style Not supported Non standard
\sub \sub
Not supported
\sube \sube
\Subset \Subset
\subset \subset
\subseteq \subseteq
\subseteqq \subseteqq
\subsetneq \subsetneq
\subsetneqq \subsetneqq
\substack $$\sum_{\substack{0<i<m\0<j<n}}$$ \sum_{\substack{0<i<m\\0<j<n}}
\succ \succ
\succapprox \succapprox
\succcurlyeq \succcurlyeq
\succeq \succeq
\succnapprox \succnapprox
\succneqq \succneqq
\succnsim \succnsim
\succsim \succsim
\sum \sum
\sup sup\sup
\supe \supe
\Supset \Supset
\supset \supset
\supseteq \supseteq
\supseteqq \supseteqq
\supsetneq \supsetneq
\supsetneqq \supsetneqq
\surd \surd
\swarrow \swarrow

T

Symbol/Function Rendered Source or Comment
\tag $$\tag{3.1c} a^2+b^2=c^2$$ \tag{3.1c} a^2+b^2=c^2
\tag* $$\tag*{3.1c} a^2+b^2=c^2$$ \tag*{3.1c} a^2+b^2=c^2
\tan tan\tan
\tanh tanh\tanh
\Tau T\Tau
\tau τ\tau
\tbinom (nk)\tbinom n k \tbinom n k
\TeX TeX\TeX
\text  yes & no \text{ yes }\&\text{ no } \text{ yes }\&\text{ no }
\textasciitilde ~\text{\textasciitilde} \text{\textasciitilde}
\textasciicircum ^\text{\textasciicircum} \text{\textasciicircum}
\textbackslash \\text{\textbackslash} \text{\textbackslash}
\textbar |\text{\textbar} \text{\textbar}
\textbardbl \text{\textbardbl} \text{\textbardbl}
\textbf AaBb123\textbf{AaBb123} \textbf{AaBb123}
\textbraceleft {\text{\textbraceleft} \text{\textbraceleft}
\textbraceright }\text{\textbraceright} \text{\textbraceright}
\textcircled a\text{\textcircled a} \text{\textcircled a}
\textcolor F=ma\textcolor{blue}{F=ma} \textcolor{blue}{F=ma}
\textdagger \text{\textdagger} \text{\textdagger}
\textdaggerdbl \text{\textdaggerdbl} \text{\textdaggerdbl}
\textdegree °\text{\textdegree} \text{\textdegree}
\textdollar $\text{\textdollar} \text{\textdollar}
\textellipsis \text{\textellipsis} \text{\textellipsis}
\textemdash \text{\textemdash} \text{\textemdash}
\textendash \text{\textendash} \text{\textendash}
\textgreater >\text{\textgreater} \text{\textgreater}
\textit AaBb\textit{AaBb} \textit{AaBb}
\textless <\text{\textless} \text{\textless}
\textmd AaBb123\textmd{AaBb123} \textmd{AaBb123}
\textnormal AB\textnormal{AB} \textnormal{AB}
\textquotedblleft \text{\textquotedblleft} \text{\textquotedblleft}
\textquotedblright \text{\textquotedblright} \text{\textquotedblright}
\textquoteleft \text{\textquoteleft} \text{\textquoteleft}
\textquoteright \text{\textquoteright} \text{\textquoteright}
\textregistered ®\text{\textregistered} \text{\textregistered}
\textrm AaBb123\textrm{AaBb123} \textrm{AaBb123}
\textsc Not supported Issue #471
\textsf AaBb123\textsf{AaBb123} \textsf{AaBb123}
\textsl Not supported
\textsterling £\text{\textsterling} \text{\textsterling}
\textstyle 0n\textstyle\sum_0^n \textstyle\sum_0^n
\texttip Not supported
\texttt AaBb123\texttt{AaBb123} \texttt{AaBb123}
\textunderscore _\text{\textunderscore} \text{\textunderscore}
\textup AaBb123\textup{AaBb123} \textup{AaBb123}
\textvisiblespace Not supported
\tfrac ab\tfrac ab \tfrac ab
\tg tg\tg
\th th\th
\therefore \therefore
\Theta Θ\Theta
\theta θ\theta
\thetasym ϑ\thetasym
\thickapprox \thickapprox
\thicksim \thicksim
\thickspace a  ba\thickspace b a\thickspace b
\thinspace aba\thinspace b a\thinspace b
\tilde M~\tilde M \tilde M
\times ×\times
\Tiny Not supported see \tiny
\tiny tiny\tiny tiny \tiny tiny
\to \to
\toggle Not supported
\top \top
\triangle \triangle
\triangledown \triangledown
\triangleleft \triangleleft
\trianglelefteq \trianglelefteq
\triangleq \triangleq
\triangleright \triangleright
\trianglerighteq \trianglerighteq
\tt AaBb123{\tt AaBb123} {\tt AaBb123}
\twoheadleftarrow \twoheadleftarrow
\twoheadrightarrow \twoheadrightarrow

U

Symbol/Function Rendered Source or Comment
\u a˘\text{\u{a}} \text{\u{a}}
\Uarr \Uarr
\uArr \uArr
\uarr \uarr
\ulcorner \ulcorner
\underbrace x++xn times\underbrace{x+⋯+x}_{n\text{ times}} \underbrace{x+⋯+x}_{n\text{ times}}
\underbracket Not supported
\undergroup AB\undergroup{AB} \undergroup{AB}
\underleftarrow AB\underleftarrow{AB} \underleftarrow{AB}
\underleftrightarrow AB\underleftrightarrow{AB} \underleftrightarrow{AB}
\underrightarrow AB\underrightarrow{AB} \underrightarrow{AB}
\underline a long argument\underline{\text{a long argument}} \underline{\text{a long argument}}
\underlinesegment ABundefined\underlinesegment{AB} \underlinesegment{AB}
\underparen Not supported See \undergroup
\underrightarrow AB\underrightarrow{AB} \underrightarrow{AB}
\underset =!\underset{!}{=} \underset{!}{=}
\unicode Not supported
\unlhd \unlhd
\unrhd \unrhd
\up Not supported
\Uparrow \Uparrow
\uparrow \uparrow
\Updownarrow \Updownarrow
\updownarrow \updownarrow
\upharpoonleft \upharpoonleft
\upharpoonright \upharpoonright
\uplus \uplus
\uproot Not supported
\upshape Not supported
\Upsilon Υ\Upsilon
\upsilon υ\upsilon
\upuparrows \upuparrows
\urcorner \urcorner
\url \url\footnotesize\url{https://katex.org/} \url{https://katex.org/} Requires trust
\utilde AB~\utilde{AB} \utilde{AB}

V

Symbol/Function Rendered Source or Comment
\v aˇ\text{\v{a}} \text{\v{a}}
\varcoppa Not supported
\varDelta Δ\varDelta
\varepsilon ε\varepsilon
\varGamma Γ\varGamma
\varinjlim Not supported
\varkappa ϰ\varkappa
\varLambda Λ\varLambda
\varliminf Not supported
\varlimsup Not supported
\varnothing \varnothing
\varOmega Ω\varOmega
\varPhi Φ\varPhi
\varphi φ\varphi
\varPi Π\varPi
\varpi ϖ\varpi
\varprojlim Not supported
\varpropto \varpropto
\varPsi Ψ\varPsi
\varPsi Ψ\varPsi
\varrho ϱ\varrho
\varSigma Σ\varSigma
\varsigma ς\varsigma
\varstigma Not supported
\varsubsetneq \varsubsetneq
\varsubsetneqq \varsubsetneqq
\varsupsetneq \varsupsetneq
\varsupsetneqq \varsupsetneqq
\varTheta Θ\varTheta
\vartheta ϑ\vartheta
\vartriangle \vartriangle
\vartriangleleft \vartriangleleft
\vartriangleright \vartriangleright
\varUpsilon Υ\varUpsilon
\varXi Ξ\varXi
\vcentcolon :\vcentcolon
\vcenter Not supported
\Vdash \Vdash
\vDash \vDash
\vdash \vdash
\vdots \vdots
\vec F\vec{F} \vec{F}
\vee \vee
\veebar \veebar
\verb \frac a b\verb!\frac a b! \verb!\frac a b!
\Vert \Vert
\vert \vert
\vfil Not supported
\vfill Not supported
\vline Not supported Issue #269
abcd\begin{Vmatrix}a&b\\c&d\end{Vmatrix} \begin{Vmatrix}
   a & b \\
   c & d
\end{Vmatrix}
abcd\begin{vmatrix}a&b\\c&d\end{vmatrix} \begin{vmatrix}
   a & b \\
   c & d
\end{vmatrix}
\vphantom Ma\overline{\vphantom{M}a} \overline{\vphantom{M}a}
\Vvdash \Vvdash

W

Symbol/Function Rendered Source or Comment
\wedge \wedge
\weierp \weierp
\widecheck ABˇ\widecheck{AB} \widecheck{AB}
\widehat AB^\widehat{AB} \widehat{AB}
\wideparen Not supported Issue #560
\widetilde AB~\widetilde{AB} \widetilde{AB}
\wp \wp
\wr \wr

X

Symbol/Function Rendered Source or Comment
\xcancel ABC\xcancel{ABC} \xcancel{ABC}
\xdef a\def\foo{a}\xdef\bar{\foo}\def\foo{}\bar \def\foo{a}\xdef\bar{\foo}\def\foo{}\bar
\Xi Ξ\Xi
\xi ξ\xi
\xhookleftarrow abc\xhookleftarrow{abc} \xhookleftarrow{abc}
\xhookrightarrow abc\xhookrightarrow{abc} \xhookrightarrow{abc}
\xLeftarrow abc\xLeftarrow{abc} \xLeftarrow{abc}
\xleftarrow abc\xleftarrow{abc} \xleftarrow{abc}
\xleftharpoondown abc\xleftharpoondown{abc} \xleftharpoondown{abc}
\xleftharpoonup abc\xleftharpoonup{abc} \xleftharpoonup{abc}
\xLeftrightarrow abc\xLeftrightarrow{abc} \xLeftrightarrow{abc}
\xleftrightarrow abc\xleftrightarrow{abc} \xleftrightarrow{abc}
\xleftrightharpoons abc\xleftrightharpoons{abc} \xleftrightharpoons{abc}
\xlongequal =abc\xlongequal{abc} \xlongequal{abc}
\xmapsto abc\xmapsto{abc} \xmapsto{abc}
\xRightarrow abc\xRightarrow{abc} \xRightarrow{abc}
\xrightarrow abc\xrightarrow{abc} \xrightarrow{abc}
\xrightharpoondown abc\xrightharpoondown{abc} \xrightharpoondown{abc}
\xrightharpoonup abc\xrightharpoonup{abc} \xrightharpoonup{abc}
\xrightleftharpoons abc\xrightleftharpoons{abc} \xrightleftharpoons{abc}
\xtofrom abc\xtofrom{abc} \xtofrom{abc}
\xtwoheadleftarrow abc\xtwoheadleftarrow{abc} \xtwoheadleftarrow{abc}
\xtwoheadrightarrow abc\xtwoheadrightarrow{abc} \xtwoheadrightarrow{abc}

YZ

Symbol/Function Rendered Source or Comment
\yen ¥\yen
\Z Z\Z
\Zeta Z\Zeta
\zeta ζ\zeta
]]>
<![CDATA[Tips to Use markdown-it-katex]]> https://note.toshiki.dev/application/markdown-it-katex/tips https://note.toshiki.dev/application/markdown-it-katex/tips Thu, 01 Jul 2021 00:00:00 GMT Tips & Hacks

1: Responsive KaTeX Styling

1.1: Issue background

KaTeX works out of the box on large screen devices such as laptops and desktop computers. But as KaTeX's built-in does not support responsiveness on it's default stylings, hence KaTeX equations might overflow out of the default width of the default application containers on small-screened mobile devices as you can see in the following image in the dev tool of chrome, when the dimension of the webpage is set to responsive or under a certain fixed device dimension, the equations rendered in KaTeX overflows out of the viewport as inspected in blue hightlight.

katex overflowing on small screen devices
◎ katex overflowing on small screen devices

This inevitably causes the viewport to break and extends the default width for KaTeX equations <div> to fit, users will be required to manually scroll right in order to view the full equation consequently as follows,

katex overflowing with labels annotated
◎ katex overflowing with labels annotated

The above situation is undoubtedly annoying for user experiences while reading documentation, consider at what scenarios users have to scroll, scroll and scroll only for viewing a single long-blocked equation, who would want to read such a text, right? But don't worry we have a simple fix for this situation via by several line of css.

1.2: Temporary solution

If you happened to search over KaTeX's official repo issue tracker on GitHub, there are several user-made css tweaks hack already, the fix is simple by adjusting the overflows of both x and y axes of the KaTeX render <div> blocks. The katex-display > .katex selector targets the child element of the .katex-display class that has the .katex class. This is the element that contains the KaTeX math expression. The first block of styles is mostly concerned with making sure that the KaTeX expression doesn't overflow its container and can be scrolled horizontally if needed. The second block of styles sets the font and line-height for the KaTeX expression and makes sure that its text is properly indented.

@preview

But, the issue here is, the overflowing issue is resolved on the webpage, but the style itself left with a slight whitish "box" at the crossing corner of both horizontal as well as vertical scrollbar tracks, this might not be so explicit in the light mode of the webpage, but when it turns to dark mode, the box become annoying. Some people might say it's an easy tweak via setting the display property of the "box" element to display: none; to directly remove the box out of the page, this is a smart approach; however, while the box is gone, the two crossing tracks is going to form an untouched invisible box again against two bars without color. Thus, neither ways seems to perfectly solve the problem.

1.3: Finding solution

After running a quick research on Google, I found a simple hack tweak used in a theme of VuePress, vuepress-theme-hope on GitHub, the theme both integrate with KaTeX and MathJax for math supports.

@preview

Under the styles directory of the repository, several line of scss styles came across my eyes,

KaTeX tweak fix styles in theme
◎ KaTeX tweak fix styles in theme

this scss lines only add a horizontal trackbar at the bottom of each overflowing equation while maximizing the vertical height of the equation, when user is on a small screened device as follows,

Horizontal scrollbar of equations on small screens
◎ Horizontal scrollbar of equations on small screen

Consequently, the fix is easy.

1.4: Solution

If you are running a documentation site like this version controlled via Node, especially VitePress without native scss supports, your fix would be installing scss support globally across the project, then add the scss styles and finally import the stylesheets to take effect globally.

Install global scss support using your favored package manager.

sh
$ npm install -D scss
$ npm install -D scss
sh
$ yarn add --dev scss
$ yarn add --dev scss
sh
$ pnpm add -D scss
$ pnpm add -D scss

Then in your scss stylesheets, add the following and link or import them to your global styles, you should be off to go with a complete fix-up for KaTeX.

scss
...

// katex responsiveness fix
.katex {
  font-size: 1.05em;
  direction: ltr;
}

.katex-display {
  overflow: auto hidden;
  -webkit-overflow-scrolling: touch;
  padding-top: 0.2em;
  padding-bottom: 0.2em;

  &::-webkit-scrollbar {
    height: 3px;
  }

  .katex {
    font-size: 1.21em;
  }
}

.katex-error {
  color: #f00;
}
// katex responsiveness fix ends

...
...

// katex responsiveness fix
.katex {
  font-size: 1.05em;
  direction: ltr;
}

.katex-display {
  overflow: auto hidden;
  -webkit-overflow-scrolling: touch;
  padding-top: 0.2em;
  padding-bottom: 0.2em;

  &::-webkit-scrollbar {
    height: 3px;
  }

  .katex {
    font-size: 1.21em;
  }
}

.katex-error {
  color: #f00;
}
// katex responsiveness fix ends

...

Next, import your styles globally to take effect,

scss
@import '<your-scss-file>.scss';
@import '<your-scss-file>.scss';

1.4.1: Fix Explanation

The first section sets the base styles for all KaTeX elements by increasing the font size slightly and ensuring that the text direction is left to right.

The second section of code targets the KaTeX display elements specifically. This section adds a bit of padding to the top and bottom of the display elements and sets overflow to auto hidden, which allows the content to scroll inside the container horizontally if it overflows the container's width. The -webkit-overflow-scrolling property is added to ensure smooth scrolling on mobile devices.

Additionally, this section contains a nested .katex selector, which increases the font size of the KaTeX elements within the display element.

The third section targets the .katex-error class and sets the color to red to indicate that there is an error in rendering the LaTeX expression.

1.5: What if I Don't Have SCSS?

If you do not have native scss support for your site, such as a static HTML based documentation site or content management site builder such as Wiki.JS that works as an SaaS which only allows users to apply custom stylesheets within slots provided and make effects, you could use some scss to css converter online with options follows,

to precompile from source scss into normal css styles and use them based on your needs, below are auto-generated compiled css, ONLY take it as reference, I do not guarantee the usability.

css
.katex {
    font-size: 1.05em;
    direction: ltr;
}

.katex-display {
    overflow: auto hidden;
    -webkit-overflow-scrolling: touch;
    padding-top: 0.2em;
    padding-bottom: 0.2em;
}
.katex-display::-webkit-scrollbar {
    height: 3px;
}
.katex-display .katex {
    font-size: 1.21em;
}

.katex-error {
    color: #f00;
}
.katex {
    font-size: 1.05em;
    direction: ltr;
}

.katex-display {
    overflow: auto hidden;
    -webkit-overflow-scrolling: touch;
    padding-top: 0.2em;
    padding-bottom: 0.2em;
}
.katex-display::-webkit-scrollbar {
    height: 3px;
}
.katex-display .katex {
    font-size: 1.21em;
}

.katex-error {
    color: #f00;
}

To be continued.

]]>
Tips & Hacks

1: Responsive KaTeX Styling

1.1: Issue background

KaTeX works out of the box on large screen devices such as laptops and desktop computers. But as KaTeX's built-in does not support responsiveness on it's default stylings, hence KaTeX equations might overflow out of the default width of the default application containers on small-screened mobile devices as you can see in the following image in the dev tool of chrome, when the dimension of the webpage is set to responsive or under a certain fixed device dimension, the equations rendered in KaTeX overflows out of the viewport as inspected in blue hightlight.

katex overflowing on small screen devices
◎ katex overflowing on small screen devices

This inevitably causes the viewport to break and extends the default width for KaTeX equations <div> to fit, users will be required to manually scroll right in order to view the full equation consequently as follows,

katex overflowing with labels annotated
◎ katex overflowing with labels annotated

The above situation is undoubtedly annoying for user experiences while reading documentation, consider at what scenarios users have to scroll, scroll and scroll only for viewing a single long-blocked equation, who would want to read such a text, right? But don't worry we have a simple fix for this situation via by several line of css.

1.2: Temporary solution

If you happened to search over KaTeX's official repo issue tracker on GitHub, there are several user-made css tweaks hack already, the fix is simple by adjusting the overflows of both x and y axes of the KaTeX render <div> blocks. The katex-display > .katex selector targets the child element of the .katex-display class that has the .katex class. This is the element that contains the KaTeX math expression. The first block of styles is mostly concerned with making sure that the KaTeX expression doesn't overflow its container and can be scrolled horizontally if needed. The second block of styles sets the font and line-height for the KaTeX expression and makes sure that its text is properly indented.

@preview

But, the issue here is, the overflowing issue is resolved on the webpage, but the style itself left with a slight whitish "box" at the crossing corner of both horizontal as well as vertical scrollbar tracks, this might not be so explicit in the light mode of the webpage, but when it turns to dark mode, the box become annoying. Some people might say it's an easy tweak via setting the display property of the "box" element to display: none; to directly remove the box out of the page, this is a smart approach; however, while the box is gone, the two crossing tracks is going to form an untouched invisible box again against two bars without color. Thus, neither ways seems to perfectly solve the problem.

1.3: Finding solution

After running a quick research on Google, I found a simple hack tweak used in a theme of VuePress, vuepress-theme-hope on GitHub, the theme both integrate with KaTeX and MathJax for math supports.

@preview

Under the styles directory of the repository, several line of scss styles came across my eyes,

KaTeX tweak fix styles in theme
◎ KaTeX tweak fix styles in theme

this scss lines only add a horizontal trackbar at the bottom of each overflowing equation while maximizing the vertical height of the equation, when user is on a small screened device as follows,

Horizontal scrollbar of equations on small screens
◎ Horizontal scrollbar of equations on small screen

Consequently, the fix is easy.

1.4: Solution

If you are running a documentation site like this version controlled via Node, especially VitePress without native scss supports, your fix would be installing scss support globally across the project, then add the scss styles and finally import the stylesheets to take effect globally.

Install global scss support using your favored package manager.

sh
$ npm install -D scss
$ npm install -D scss
sh
$ yarn add --dev scss
$ yarn add --dev scss
sh
$ pnpm add -D scss
$ pnpm add -D scss

Then in your scss stylesheets, add the following and link or import them to your global styles, you should be off to go with a complete fix-up for KaTeX.

scss
...

// katex responsiveness fix
.katex {
  font-size: 1.05em;
  direction: ltr;
}

.katex-display {
  overflow: auto hidden;
  -webkit-overflow-scrolling: touch;
  padding-top: 0.2em;
  padding-bottom: 0.2em;

  &::-webkit-scrollbar {
    height: 3px;
  }

  .katex {
    font-size: 1.21em;
  }
}

.katex-error {
  color: #f00;
}
// katex responsiveness fix ends

...
...

// katex responsiveness fix
.katex {
  font-size: 1.05em;
  direction: ltr;
}

.katex-display {
  overflow: auto hidden;
  -webkit-overflow-scrolling: touch;
  padding-top: 0.2em;
  padding-bottom: 0.2em;

  &::-webkit-scrollbar {
    height: 3px;
  }

  .katex {
    font-size: 1.21em;
  }
}

.katex-error {
  color: #f00;
}
// katex responsiveness fix ends

...

Next, import your styles globally to take effect,

scss
@import '<your-scss-file>.scss';
@import '<your-scss-file>.scss';

1.4.1: Fix Explanation

The first section sets the base styles for all KaTeX elements by increasing the font size slightly and ensuring that the text direction is left to right.

The second section of code targets the KaTeX display elements specifically. This section adds a bit of padding to the top and bottom of the display elements and sets overflow to auto hidden, which allows the content to scroll inside the container horizontally if it overflows the container's width. The -webkit-overflow-scrolling property is added to ensure smooth scrolling on mobile devices.

Additionally, this section contains a nested .katex selector, which increases the font size of the KaTeX elements within the display element.

The third section targets the .katex-error class and sets the color to red to indicate that there is an error in rendering the LaTeX expression.

1.5: What if I Don't Have SCSS?

If you do not have native scss support for your site, such as a static HTML based documentation site or content management site builder such as Wiki.JS that works as an SaaS which only allows users to apply custom stylesheets within slots provided and make effects, you could use some scss to css converter online with options follows,

to precompile from source scss into normal css styles and use them based on your needs, below are auto-generated compiled css, ONLY take it as reference, I do not guarantee the usability.

css
.katex {
    font-size: 1.05em;
    direction: ltr;
}

.katex-display {
    overflow: auto hidden;
    -webkit-overflow-scrolling: touch;
    padding-top: 0.2em;
    padding-bottom: 0.2em;
}
.katex-display::-webkit-scrollbar {
    height: 3px;
}
.katex-display .katex {
    font-size: 1.21em;
}

.katex-error {
    color: #f00;
}
.katex {
    font-size: 1.05em;
    direction: ltr;
}

.katex-display {
    overflow: auto hidden;
    -webkit-overflow-scrolling: touch;
    padding-top: 0.2em;
    padding-bottom: 0.2em;
}
.katex-display::-webkit-scrollbar {
    height: 3px;
}
.katex-display .katex {
    font-size: 1.21em;
}

.katex-error {
    color: #f00;
}

To be continued.

]]>
<![CDATA[Meta Annotations]]> https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/api/annotations https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/api/annotations Thu, 01 Jul 2021 00:00:00 GMT Queries

Sometimes the thing you want to say is about the code, annotations provide a way to provide outside commentary on your code.

@annotate: [left|right] [overrides] - [text]

Annotate has a lot more controls than most of the other Twoslash commands, because each use of it probably needs to feel a bit different. Here's an example based on the TypeScript home page, click it to get it running so we can talk about what it does:

ts
ts
function compact(arr) {
if (orr.length > 10) return arr.trim(0, 10)
Cannot find name 'orr'.2304Cannot find name 'orr'.
return arr
}

Discovered a typo, the param is arr, not orr!

ts
function compact(arr) {
if (orr.length > 10) return arr.trim(0, 10)
Cannot find name 'orr'.2304Cannot find name 'orr'.
return arr
}

Discovered a typo, the param is arr, not orr!

md
```ts twoslash
// @errors: 2304
// @strict: false

function compact(arr) {
    if (orr.length > 10) return arr.trim(0, 10)
    return arr
}
// @annotate: left { "arrowRot": "90deg 8px 27px", "textDegree": "3deg", "top": "0rem" } - Discovered a typo, the param is arr, not orr!
```
```ts twoslash
// @errors: 2304
// @strict: false

function compact(arr) {
    if (orr.length > 10) return arr.trim(0, 10)
    return arr
}
// @annotate: left { "arrowRot": "90deg 8px 27px", "textDegree": "3deg", "top": "0rem" } - Discovered a typo, the param is arr, not orr!
```

First up, cool — it adds some text to the left hand side of the code. It features quite a few different options, so lets go through them one by one:

  • left or right: It's currently left. It's worth noting the arrow flips also, and 90deg isn't a great option. Let's look at that next.

  • { "arrrowRot": "90deg 8px 27px" } - This JSON object is used to manipulate the annotation, you have 3 controls for arrow positioning and rotation: degrees x y. I recommend keeping those in degrees and px, but it's your life. These are overrides from defaults which are okay, but not really something you ever want to ship.

  • { "textDegree": "3deg" } - Rotates the text, you probably want something between -3deg and 3deg. Optional, defaults to 0.

  • { "top": "0rem" } - Sets the y coordinates for the annotation relative to the code sample, if it's not included then it becomes [lineNum]rem.

What's not included in this sample is flipped, which can be used to flip the arrow's orientation. Here's some examples:

A horizontal right example:

ts
ts
function compact(arr) {
if (orr.length > 10) return arr.trim(0, 10)
Cannot find name 'orr'.2304Cannot find name 'orr'.
return arr
}

Discovered a typo, the param is arr, not orr!

ts
function compact(arr) {
if (orr.length > 10) return arr.trim(0, 10)
Cannot find name 'orr'.2304Cannot find name 'orr'.
return arr
}

Discovered a typo, the param is arr, not orr!

md
```ts twoslash
// @errors: 2304
// @strict: false

function compact(arr) {
    if (orr.length > 10) return arr.trim(0, 10)
    return arr
}
// @annotate: left { "arrowRot": "90deg 8px 27px", "textDegree": "3deg", "top": "0rem" } - Discovered a typo, the param is arr, not orr!
```
```ts twoslash
// @errors: 2304
// @strict: false

function compact(arr) {
    if (orr.length > 10) return arr.trim(0, 10)
    return arr
}
// @annotate: left { "arrowRot": "90deg 8px 27px", "textDegree": "3deg", "top": "0rem" } - Discovered a typo, the param is arr, not orr!
```

Upside down arrow pointing at the error, using flipped to re-flip the arrow:

ts
ts
function compact(arr) {
if (orr.length > 10) return arr.trim(0, 10)
Cannot find name 'orr'.2304Cannot find name 'orr'.
return arr
}

Discovered a typo, the param is arr, not orr!

ts
function compact(arr) {
if (orr.length > 10) return arr.trim(0, 10)
Cannot find name 'orr'.2304Cannot find name 'orr'.
return arr
}

Discovered a typo, the param is arr, not orr!

md
```ts twoslash
// @errors: 2304
// @strict: false

function compact(arr) {
    if (orr.length > 10) return arr.trim(0, 10)
    return arr
}
// @annotate: left { "arrowRot": "90deg 8px 27px", "textDegree": "3deg", "top": "0rem" } - Discovered a typo, the param is arr, not orr!
```
```ts twoslash
// @errors: 2304
// @strict: false

function compact(arr) {
    if (orr.length > 10) return arr.trim(0, 10)
    return arr
}
// @annotate: left { "arrowRot": "90deg 8px 27px", "textDegree": "3deg", "top": "0rem" } - Discovered a typo, the param is arr, not orr!
```
]]>
Queries

Sometimes the thing you want to say is about the code, annotations provide a way to provide outside commentary on your code.

@annotate: [left|right] [overrides] - [text]

Annotate has a lot more controls than most of the other Twoslash commands, because each use of it probably needs to feel a bit different. Here's an example based on the TypeScript home page, click it to get it running so we can talk about what it does:

ts
ts
function compact(arr) {
if (orr.length > 10) return arr.trim(0, 10)
Cannot find name 'orr'.2304Cannot find name 'orr'.
return arr
}

Discovered a typo, the param is arr, not orr!

ts
function compact(arr) {
if (orr.length > 10) return arr.trim(0, 10)
Cannot find name 'orr'.2304Cannot find name 'orr'.
return arr
}

Discovered a typo, the param is arr, not orr!

md
```ts twoslash
// @errors: 2304
// @strict: false

function compact(arr) {
    if (orr.length > 10) return arr.trim(0, 10)
    return arr
}
// @annotate: left { "arrowRot": "90deg 8px 27px", "textDegree": "3deg", "top": "0rem" } - Discovered a typo, the param is arr, not orr!
```
```ts twoslash
// @errors: 2304
// @strict: false

function compact(arr) {
    if (orr.length > 10) return arr.trim(0, 10)
    return arr
}
// @annotate: left { "arrowRot": "90deg 8px 27px", "textDegree": "3deg", "top": "0rem" } - Discovered a typo, the param is arr, not orr!
```

First up, cool — it adds some text to the left hand side of the code. It features quite a few different options, so lets go through them one by one:

  • left or right: It's currently left. It's worth noting the arrow flips also, and 90deg isn't a great option. Let's look at that next.

  • { "arrrowRot": "90deg 8px 27px" } - This JSON object is used to manipulate the annotation, you have 3 controls for arrow positioning and rotation: degrees x y. I recommend keeping those in degrees and px, but it's your life. These are overrides from defaults which are okay, but not really something you ever want to ship.

  • { "textDegree": "3deg" } - Rotates the text, you probably want something between -3deg and 3deg. Optional, defaults to 0.

  • { "top": "0rem" } - Sets the y coordinates for the annotation relative to the code sample, if it's not included then it becomes [lineNum]rem.

What's not included in this sample is flipped, which can be used to flip the arrow's orientation. Here's some examples:

A horizontal right example:

ts
ts
function compact(arr) {
if (orr.length > 10) return arr.trim(0, 10)
Cannot find name 'orr'.2304Cannot find name 'orr'.
return arr
}

Discovered a typo, the param is arr, not orr!

ts
function compact(arr) {
if (orr.length > 10) return arr.trim(0, 10)
Cannot find name 'orr'.2304Cannot find name 'orr'.
return arr
}

Discovered a typo, the param is arr, not orr!

md
```ts twoslash
// @errors: 2304
// @strict: false

function compact(arr) {
    if (orr.length > 10) return arr.trim(0, 10)
    return arr
}
// @annotate: left { "arrowRot": "90deg 8px 27px", "textDegree": "3deg", "top": "0rem" } - Discovered a typo, the param is arr, not orr!
```
```ts twoslash
// @errors: 2304
// @strict: false

function compact(arr) {
    if (orr.length > 10) return arr.trim(0, 10)
    return arr
}
// @annotate: left { "arrowRot": "90deg 8px 27px", "textDegree": "3deg", "top": "0rem" } - Discovered a typo, the param is arr, not orr!
```

Upside down arrow pointing at the error, using flipped to re-flip the arrow:

ts
ts
function compact(arr) {
if (orr.length > 10) return arr.trim(0, 10)
Cannot find name 'orr'.2304Cannot find name 'orr'.
return arr
}

Discovered a typo, the param is arr, not orr!

ts
function compact(arr) {
if (orr.length > 10) return arr.trim(0, 10)
Cannot find name 'orr'.2304Cannot find name 'orr'.
return arr
}

Discovered a typo, the param is arr, not orr!

md
```ts twoslash
// @errors: 2304
// @strict: false

function compact(arr) {
    if (orr.length > 10) return arr.trim(0, 10)
    return arr
}
// @annotate: left { "arrowRot": "90deg 8px 27px", "textDegree": "3deg", "top": "0rem" } - Discovered a typo, the param is arr, not orr!
```
```ts twoslash
// @errors: 2304
// @strict: false

function compact(arr) {
    if (orr.length > 10) return arr.trim(0, 10)
    return arr
}
// @annotate: left { "arrowRot": "90deg 8px 27px", "textDegree": "3deg", "top": "0rem" } - Discovered a typo, the param is arr, not orr!
```
]]>
<![CDATA[Cutting]]> https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/api/cutting https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/api/cutting Thu, 01 Jul 2021 00:00:00 GMT Cutting

Every Twoslash code example needs to be a complete TypeScript program so it can compile. Quite often to make it compile, there is a bunch of code which isn't relevant to the user. This can be extracted out of the code examples via cut comments.

---cut---

Cut works after TypeScript has generated the project and pulled out all the editor information (like identifiers, queries, highlights etc) and then amends all of their offsets and lines to re-fit the smaller output. What your user sees is everything below the ---cut---.

ts
ts
console.log(level)
ts
console.log(level)
md
```ts twoslash
const level: string = 'Danger'
// ---cut---
console.log(level)
```
```ts twoslash
const level: string = 'Danger'
// ---cut---
console.log(level)
```

Cutting even works across multiple files. This is why // @filename: [file] is specifically the only Twoslash command which is not removed, because if it's not relevant it can be ---cut--- away.

ts
ts
import { helloWorld } from './a'
console.log(helloWorld)
ts
import { helloWorld } from './a'
console.log(helloWorld)
md
```ts twoslash
// @filename: a.ts
export const helloWorld: string = 'Hi'

// @filename: b.ts
// ---cut---
import { helloWorld } from './a'
console.log(helloWorld)
```
```ts twoslash
// @filename: a.ts
export const helloWorld: string = 'Hi'

// @filename: b.ts
// ---cut---
import { helloWorld } from './a'
console.log(helloWorld)
```

---cut-after---

The sibling to ---cut---, which trims anything after the sigil:

tsx
tsx
<Container>
<ImportantComponent />
</Container>
tsx
<Container>
<ImportantComponent />
</Container>
md
```tsx twoslash
const Page = () => (
    // ---cut---
    <Container>
        <ImportantComponent />
    </Container>
    // ---cut-after---
)
```
```tsx twoslash
const Page = () => (
    // ---cut---
    <Container>
        <ImportantComponent />
    </Container>
    // ---cut-after---
)
```
]]>
Cutting

Every Twoslash code example needs to be a complete TypeScript program so it can compile. Quite often to make it compile, there is a bunch of code which isn't relevant to the user. This can be extracted out of the code examples via cut comments.

---cut---

Cut works after TypeScript has generated the project and pulled out all the editor information (like identifiers, queries, highlights etc) and then amends all of their offsets and lines to re-fit the smaller output. What your user sees is everything below the ---cut---.

ts
ts
console.log(level)
ts
console.log(level)
md
```ts twoslash
const level: string = 'Danger'
// ---cut---
console.log(level)
```
```ts twoslash
const level: string = 'Danger'
// ---cut---
console.log(level)
```

Cutting even works across multiple files. This is why // @filename: [file] is specifically the only Twoslash command which is not removed, because if it's not relevant it can be ---cut--- away.

ts
ts
import { helloWorld } from './a'
console.log(helloWorld)
ts
import { helloWorld } from './a'
console.log(helloWorld)
md
```ts twoslash
// @filename: a.ts
export const helloWorld: string = 'Hi'

// @filename: b.ts
// ---cut---
import { helloWorld } from './a'
console.log(helloWorld)
```
```ts twoslash
// @filename: a.ts
export const helloWorld: string = 'Hi'

// @filename: b.ts
// ---cut---
import { helloWorld } from './a'
console.log(helloWorld)
```

---cut-after---

The sibling to ---cut---, which trims anything after the sigil:

tsx
tsx
<Container>
<ImportantComponent />
</Container>
tsx
<Container>
<ImportantComponent />
</Container>
md
```tsx twoslash
const Page = () => (
    // ---cut---
    <Container>
        <ImportantComponent />
    </Container>
    // ---cut-after---
)
```
```tsx twoslash
const Page = () => (
    // ---cut---
    <Container>
        <ImportantComponent />
    </Container>
    // ---cut-after---
)
```
]]>
<![CDATA[Emit]]> https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/api/emit https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/api/emit Thu, 01 Jul 2021 00:00:00 GMT Emit

Running a Twoslash code example is a full TypeScript compiler run that will create files inside the virtual file system. You can replace the contents of your code examples with the results of running TypeScript over the project.

@showEmit

// @showEmit is the main command to tell Shiki Twoslash that you want to replace the output of your code example with the equivalent .js file.

ts
ts
"use strict";
const level = 'Danger';
 
ts
"use strict";
const level = 'Danger';
 
md
```ts twoslash
// @showEmit
const level: string = 'Danger'
```
```ts twoslash
// @showEmit
const level: string = 'Danger'
```

@showEmittedFile: [file]

While the .js file is probably the most useful file out of the box, TypeScript does emit other files if you have the right flags enabled (.d.ts and .map) but also when you have a multi-file code sample — you might need to tell Twoslash which file to show. For all these cases you can also add @showEmittedFile: [file] to tell Twoslash which file you want to show.

Shows emitted .d.ts for a TypeScript code example:

md
```ts twoslash
// @declaration
// @showEmit
// @showEmittedFile: index.d.ts
export const hello = 'world'
```
```ts twoslash
// @declaration
// @showEmit
// @showEmittedFile: index.d.ts
export const hello = 'world'
```
ts
ts
export declare const hello = "world";
 
ts
export declare const hello = "world";
 

Shows emitted .map files:

md
```ts twoslash
// @sourceMap
// @showEmit
// @showEmittedFile: index.js.map
export const hello = 'world'
```
```ts twoslash
// @sourceMap
// @showEmit
// @showEmittedFile: index.js.map
export const hello = 'world'
```
ts
ts
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,KAAK,GAAG,OAAO,CAAA"}
ts
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,KAAK,GAAG,OAAO,CAAA"}
md
```ts twoslash
// @declaration
// @declarationMap
// @showEmit
// @showEmittedFile: index.d.ts.map
export const hello = 'world'
```
```ts twoslash
// @declaration
// @declarationMap
// @showEmit
// @showEmittedFile: index.d.ts.map
export const hello = 'world'
```
ts
ts
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,KAAK,UAAU,CAAA"}
ts
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,KAAK,UAAU,CAAA"}
]]>
Emit

Running a Twoslash code example is a full TypeScript compiler run that will create files inside the virtual file system. You can replace the contents of your code examples with the results of running TypeScript over the project.

@showEmit

// @showEmit is the main command to tell Shiki Twoslash that you want to replace the output of your code example with the equivalent .js file.

ts
ts
"use strict";
const level = 'Danger';
 
ts
"use strict";
const level = 'Danger';
 
md
```ts twoslash
// @showEmit
const level: string = 'Danger'
```
```ts twoslash
// @showEmit
const level: string = 'Danger'
```

@showEmittedFile: [file]

While the .js file is probably the most useful file out of the box, TypeScript does emit other files if you have the right flags enabled (.d.ts and .map) but also when you have a multi-file code sample — you might need to tell Twoslash which file to show. For all these cases you can also add @showEmittedFile: [file] to tell Twoslash which file you want to show.

Shows emitted .d.ts for a TypeScript code example:

md
```ts twoslash
// @declaration
// @showEmit
// @showEmittedFile: index.d.ts
export const hello = 'world'
```
```ts twoslash
// @declaration
// @showEmit
// @showEmittedFile: index.d.ts
export const hello = 'world'
```
ts
ts
export declare const hello = "world";
 
ts
export declare const hello = "world";
 

Shows emitted .map files:

md
```ts twoslash
// @sourceMap
// @showEmit
// @showEmittedFile: index.js.map
export const hello = 'world'
```
```ts twoslash
// @sourceMap
// @showEmit
// @showEmittedFile: index.js.map
export const hello = 'world'
```
ts
ts
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,KAAK,GAAG,OAAO,CAAA"}
ts
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,KAAK,GAAG,OAAO,CAAA"}
md
```ts twoslash
// @declaration
// @declarationMap
// @showEmit
// @showEmittedFile: index.d.ts.map
export const hello = 'world'
```
```ts twoslash
// @declaration
// @declarationMap
// @showEmit
// @showEmittedFile: index.d.ts.map
export const hello = 'world'
```
ts
ts
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,KAAK,UAAU,CAAA"}
ts
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,KAAK,UAAU,CAAA"}
]]>
<![CDATA[Errors]]> https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/api/errors https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/api/errors Thu, 01 Jul 2021 00:00:00 GMT Errors

Most of the time, you want to avoid errors in your code examples. Strictly speaking, this usually means setting the right compiler flags and environment in each code example.

Sometimes however, you do want to raise a compiler error — to show incorrect states. In those cases, twoslash has a way to mark the compiler errors you expect.

@errors: [num]

All TypeScript compiler errors have a number, this number is relatively arbitrary and can change between TypeScript versions. For our case these numbers are useul in declaring what we expect to see.

You can use // @errors: [num] to tell Twoslash that you expect this error to occur. This moves the compiler error message into the code example.

ts
ts
const a = '123'
a = 132
Cannot assign to 'a' because it is a constant.2588Cannot assign to 'a' because it is a constant.
ts
const a = '123'
a = 132
Cannot assign to 'a' because it is a constant.2588Cannot assign to 'a' because it is a constant.
md
```ts twoslash
// @errors: 2588
const a = '123'
a = 132
```
```ts twoslash
// @errors: 2588
const a = '123'
a = 132
```

@noErrors

Sometimes you have needs in which a broken TypeScript build is okay. A good example of this is using a completion query, which requires a broken TypeScript project to work. You can use // @noErrors to supress all errors in a code sample, and not have them show inline.

ts
ts
const a = '123'
a = 132
ts
const a = '123'
a = 132
md
```ts twoslash
// @noErrors
const a = '123'
a = 132
```
```ts twoslash
// @noErrors
const a = '123'
a = 132
```
]]>
Errors

Most of the time, you want to avoid errors in your code examples. Strictly speaking, this usually means setting the right compiler flags and environment in each code example.

Sometimes however, you do want to raise a compiler error — to show incorrect states. In those cases, twoslash has a way to mark the compiler errors you expect.

@errors: [num]

All TypeScript compiler errors have a number, this number is relatively arbitrary and can change between TypeScript versions. For our case these numbers are useul in declaring what we expect to see.

You can use // @errors: [num] to tell Twoslash that you expect this error to occur. This moves the compiler error message into the code example.

ts
ts
const a = '123'
a = 132
Cannot assign to 'a' because it is a constant.2588Cannot assign to 'a' because it is a constant.
ts
const a = '123'
a = 132
Cannot assign to 'a' because it is a constant.2588Cannot assign to 'a' because it is a constant.
md
```ts twoslash
// @errors: 2588
const a = '123'
a = 132
```
```ts twoslash
// @errors: 2588
const a = '123'
a = 132
```

@noErrors

Sometimes you have needs in which a broken TypeScript build is okay. A good example of this is using a completion query, which requires a broken TypeScript project to work. You can use // @noErrors to supress all errors in a code sample, and not have them show inline.

ts
ts
const a = '123'
a = 132
ts
const a = '123'
a = 132
md
```ts twoslash
// @noErrors
const a = '123'
a = 132
```
```ts twoslash
// @noErrors
const a = '123'
a = 132
```
]]>
<![CDATA[Includes]]> https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/api/includes https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/api/includes Thu, 01 Jul 2021 00:00:00 GMT Includes

As your documentation grows, you may need a way of re-using code blocks to prevent code duplication. Shiki Twoslash provides a simple includes system.

Defining a re-usable block

Re-usable code blocks are defined by the twoslash language, followed by the include keyword and the reference name of your choice.

md
```twoslash include myBlock
type SomeString = string
```
```twoslash include myBlock
type SomeString = string
```

Incremental steps

Shiki Twoslash also provide the ability to define incremental steps through the definition of re-usable blocks. This means whenever a new step is delimited down the code, it will also include previous steps. These are not groups.

  • Incremental steps are delimited by // - [name of the step]
  • They are named at the end of the actual code
md
```twoslash include myBlockWithSteps
type SomeString = string
// - base
type SomeUser = { name: string; mail?: SomeUserMail }
type SomeUserMail = { content: string; verified: boolean }
// - afterUserDefinitions
type SomeGroup = { name: string; members: SomeUser[] }
// - afterGroupDefinitions
```
```twoslash include myBlockWithSteps
type SomeString = string
// - base
type SomeUser = { name: string; mail?: SomeUserMail }
type SomeUserMail = { content: string; verified: boolean }
// - afterUserDefinitions
type SomeGroup = { name: string; members: SomeUser[] }
// - afterGroupDefinitions
```

Including a whole block

To include a re-usable block, add // @include: [block name] in your code block.

twoslash
ts
ts
type SomeString = string
const a: SomeString = 'string'
ts
type SomeString = string
const a: SomeString = 'string'
md
```twoslash include myBlock
type SomeString = string
```

```ts twoslash
// @include: myBlock
const a: SomeString = 'string'
```
```twoslash include myBlock
type SomeString = string
```

```ts twoslash
// @include: myBlock
const a: SomeString = 'string'
```

Including a block step

To include a re-usable block at a specific step, add // @include: [block name]-[step name] in your code block.

twoslash
ts
ts
type SomeString = string
type SomeUser = { name: string; mail?: SomeUserMail }
type SomeUserMail = { content: string; verified: boolean }
const mail: SomeUserMail = { content: 'some-email', verified: true }
ts
type SomeString = string
type SomeUser = { name: string; mail?: SomeUserMail }
type SomeUserMail = { content: string; verified: boolean }
const mail: SomeUserMail = { content: 'some-email', verified: true }
md
```twoslash include myBlockWithSteps
type SomeString = string
// - base
type SomeUser = { name: string; mail?: SomeUserMail }
type SomeUserMail = { content: string; verified: boolean }
// - afterUserDefinitions
type SomeGroup = { name: string; members: SomeUser[] }
// - afterGroupDefinitions
```

```ts twoslash
// @include: myBlockWithSteps-afterUserDefinitions
const mail: SomeUserMail = { content: 'some-email', verified: true }
```
```twoslash include myBlockWithSteps
type SomeString = string
// - base
type SomeUser = { name: string; mail?: SomeUserMail }
type SomeUserMail = { content: string; verified: boolean }
// - afterUserDefinitions
type SomeGroup = { name: string; members: SomeUser[] }
// - afterGroupDefinitions
```

```ts twoslash
// @include: myBlockWithSteps-afterUserDefinitions
const mail: SomeUserMail = { content: 'some-email', verified: true }
```

Hiding re-used code

Re-using a lot of TypeScript code can easily bloat your documentation and obstruct the main point of your code block. You can hide re-used code to keep your code blocks clean and concise by cutting right after the @include statement.

ts
ts
const mail: SomeUserMail = { content: 'some-email', verified: true }
ts
const mail: SomeUserMail = { content: 'some-email', verified: true }
md
```twoslash include myBlockWithSteps
type SomeString = string
// - base
type SomeUser = { name: string; mail?: SomeUserMail }
type SomeUserMail = { content: string; verified: boolean }
// - afterUserDefinitions
type SomeGroup = { name: string; members: SomeUser[] }
// - afterGroupDefinitions
```

```ts twoslash
// @include: myBlockWithSteps-afterUserDefinitions
// ---cut---
const mail: SomeUserMail = { content: 'some-email', verified: true }
```
```twoslash include myBlockWithSteps
type SomeString = string
// - base
type SomeUser = { name: string; mail?: SomeUserMail }
type SomeUserMail = { content: string; verified: boolean }
// - afterUserDefinitions
type SomeGroup = { name: string; members: SomeUser[] }
// - afterGroupDefinitions
```

```ts twoslash
// @include: myBlockWithSteps-afterUserDefinitions
// ---cut---
const mail: SomeUserMail = { content: 'some-email', verified: true }
```
]]>
Includes

As your documentation grows, you may need a way of re-using code blocks to prevent code duplication. Shiki Twoslash provides a simple includes system.

Defining a re-usable block

Re-usable code blocks are defined by the twoslash language, followed by the include keyword and the reference name of your choice.

md
```twoslash include myBlock
type SomeString = string
```
```twoslash include myBlock
type SomeString = string
```

Incremental steps

Shiki Twoslash also provide the ability to define incremental steps through the definition of re-usable blocks. This means whenever a new step is delimited down the code, it will also include previous steps. These are not groups.

  • Incremental steps are delimited by // - [name of the step]
  • They are named at the end of the actual code
md
```twoslash include myBlockWithSteps
type SomeString = string
// - base
type SomeUser = { name: string; mail?: SomeUserMail }
type SomeUserMail = { content: string; verified: boolean }
// - afterUserDefinitions
type SomeGroup = { name: string; members: SomeUser[] }
// - afterGroupDefinitions
```
```twoslash include myBlockWithSteps
type SomeString = string
// - base
type SomeUser = { name: string; mail?: SomeUserMail }
type SomeUserMail = { content: string; verified: boolean }
// - afterUserDefinitions
type SomeGroup = { name: string; members: SomeUser[] }
// - afterGroupDefinitions
```

Including a whole block

To include a re-usable block, add // @include: [block name] in your code block.

twoslash
ts
ts
type SomeString = string
const a: SomeString = 'string'
ts
type SomeString = string
const a: SomeString = 'string'
md
```twoslash include myBlock
type SomeString = string
```

```ts twoslash
// @include: myBlock
const a: SomeString = 'string'
```
```twoslash include myBlock
type SomeString = string
```

```ts twoslash
// @include: myBlock
const a: SomeString = 'string'
```

Including a block step

To include a re-usable block at a specific step, add // @include: [block name]-[step name] in your code block.

twoslash
ts
ts
type SomeString = string
type SomeUser = { name: string; mail?: SomeUserMail }
type SomeUserMail = { content: string; verified: boolean }
const mail: SomeUserMail = { content: 'some-email', verified: true }
ts
type SomeString = string
type SomeUser = { name: string; mail?: SomeUserMail }
type SomeUserMail = { content: string; verified: boolean }
const mail: SomeUserMail = { content: 'some-email', verified: true }
md
```twoslash include myBlockWithSteps
type SomeString = string
// - base
type SomeUser = { name: string; mail?: SomeUserMail }
type SomeUserMail = { content: string; verified: boolean }
// - afterUserDefinitions
type SomeGroup = { name: string; members: SomeUser[] }
// - afterGroupDefinitions
```

```ts twoslash
// @include: myBlockWithSteps-afterUserDefinitions
const mail: SomeUserMail = { content: 'some-email', verified: true }
```
```twoslash include myBlockWithSteps
type SomeString = string
// - base
type SomeUser = { name: string; mail?: SomeUserMail }
type SomeUserMail = { content: string; verified: boolean }
// - afterUserDefinitions
type SomeGroup = { name: string; members: SomeUser[] }
// - afterGroupDefinitions
```

```ts twoslash
// @include: myBlockWithSteps-afterUserDefinitions
const mail: SomeUserMail = { content: 'some-email', verified: true }
```

Hiding re-used code

Re-using a lot of TypeScript code can easily bloat your documentation and obstruct the main point of your code block. You can hide re-used code to keep your code blocks clean and concise by cutting right after the @include statement.

ts
ts
const mail: SomeUserMail = { content: 'some-email', verified: true }
ts
const mail: SomeUserMail = { content: 'some-email', verified: true }
md
```twoslash include myBlockWithSteps
type SomeString = string
// - base
type SomeUser = { name: string; mail?: SomeUserMail }
type SomeUserMail = { content: string; verified: boolean }
// - afterUserDefinitions
type SomeGroup = { name: string; members: SomeUser[] }
// - afterGroupDefinitions
```

```ts twoslash
// @include: myBlockWithSteps-afterUserDefinitions
// ---cut---
const mail: SomeUserMail = { content: 'some-email', verified: true }
```
```twoslash include myBlockWithSteps
type SomeString = string
// - base
type SomeUser = { name: string; mail?: SomeUserMail }
type SomeUserMail = { content: string; verified: boolean }
// - afterUserDefinitions
type SomeGroup = { name: string; members: SomeUser[] }
// - afterGroupDefinitions
```

```ts twoslash
// @include: myBlockWithSteps-afterUserDefinitions
// ---cut---
const mail: SomeUserMail = { content: 'some-email', verified: true }
```
]]>
<![CDATA[Logging]]> https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/api/logging https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/api/logging Thu, 01 Jul 2021 00:00:00 GMT Logging

When you first see a Twoslash code example with an inline compiler error, you instinctively trust that the compiler error is correct because the design shows that it is not a part of the code sample. The logging tools lets you do that, but abuses the systemic trust because your code is not being evaluated to generate the logs.

This feature is effectively a facade, people will trust your output and it will look better.

@log:, @warn:, @error:

The names are based on the functions on the console object:

ts
ts
console.log('Hello log')
Hello log
 
console.warn('Hello warn')
Hello warn
 
console.error('Hello error')
Hello error
ts
console.log('Hello log')
Hello log
 
console.warn('Hello warn')
Hello warn
 
console.error('Hello error')
Hello error
md
```ts twoslash
console.log('Hello log')
// @log: Hello log

console.warn('Hello warn')
// @warn: Hello warn

console.error('Hello error')
// @error: Hello error
```
```ts twoslash
console.log('Hello log')
// @log: Hello log

console.warn('Hello warn')
// @warn: Hello warn

console.error('Hello error')
// @error: Hello error
```
]]>
Logging

When you first see a Twoslash code example with an inline compiler error, you instinctively trust that the compiler error is correct because the design shows that it is not a part of the code sample. The logging tools lets you do that, but abuses the systemic trust because your code is not being evaluated to generate the logs.

This feature is effectively a facade, people will trust your output and it will look better.

@log:, @warn:, @error:

The names are based on the functions on the console object:

ts
ts
console.log('Hello log')
Hello log
 
console.warn('Hello warn')
Hello warn
 
console.error('Hello error')
Hello error
ts
console.log('Hello log')
Hello log
 
console.warn('Hello warn')
Hello warn
 
console.error('Hello error')
Hello error
md
```ts twoslash
console.log('Hello log')
// @log: Hello log

console.warn('Hello warn')
// @warn: Hello warn

console.error('Hello error')
// @error: Hello error
```
```ts twoslash
console.log('Hello log')
// @log: Hello log

console.warn('Hello warn')
// @warn: Hello warn

console.error('Hello error')
// @error: Hello error
```
]]>
<![CDATA[Multi-file]]> https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/api/multi-file https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/api/multi-file Thu, 01 Jul 2021 00:00:00 GMT Multi-file

Twoslash code examples aren't limited to creating a single file, by using // @filename: [file] you can write any file to the virtual file system used by TypeScript to power your code examples.

@filename: [file]

Most of the time, you don't need to think about the underlaying virtual file system in a code example, but when you have imports between them it becomes important to know. Twoslash will default to creating an index.[type] based on the langauge passed to the code example:

ts
ts
// I'm index.ts
ts
// I'm index.ts
md
```ts twoslash
// I'm index.ts
```
```ts twoslash
// I'm index.ts
```
tsx
tsx
// I'm index.tsx
tsx
// I'm index.tsx
md
```tsx twoslash
// I'm index.tsx
```
```tsx twoslash
// I'm index.tsx
```
js
js
// I'm index.tjs
js
// I'm index.tjs
md
```js twoslash
// I'm index.tjs
```
```js twoslash
// I'm index.tjs
```

Then until Twoslash hits another // @filename: [file], the parser keeps adding new lines into the same file. After seeing @filename Twoslash creates a new virtual file-system file and adds the new lines to that. You can't edit a file after it was created, but you can overwrite it.

It can be any file. For example, if you want to quickly fake a node module:

ts
ts
// @filename: node_modules/@types/mylib/index.d.ts
export function doit(): string
 
// @filename: index.ts
import { doit } from 'mylib'
console.log(doit)
ts
// @filename: node_modules/@types/mylib/index.d.ts
export function doit(): string
 
// @filename: index.ts
import { doit } from 'mylib'
console.log(doit)

This code example sets up the types for a non-existent npm module, and TypeScript picks it up as the definitions in the same way it would in a non-virtual TypeScript project.

md
```ts twoslash
// @filename: node_modules/@types/mylib/index.d.ts
export function doit(): string

// @filename: index.ts
import { doit } from 'mylib'
console.log(doit)
```
```ts twoslash
// @filename: node_modules/@types/mylib/index.d.ts
export function doit(): string

// @filename: index.ts
import { doit } from 'mylib'
console.log(doit)
```

You can also set up a JSON object which can be imported in a TypeScript file:

ts
ts
// @filename: app.json
{ "version": "23.2.3" }
 
// @filename: index.ts
import appSettings from "./app.json"
appSettings.version
(property) "version": string
ts
// @filename: app.json
{ "version": "23.2.3" }
 
// @filename: index.ts
import appSettings from "./app.json"
appSettings.version
(property) "version": string
md
```ts twoslash
// @resolveJsonModule
// @filename: app.json
{ "version": "23.2.3" }

// @filename: index.ts
import appSettings from "./app.json"
appSettings.version
//           ^?
```
```ts twoslash
// @resolveJsonModule
// @filename: app.json
{ "version": "23.2.3" }

// @filename: index.ts
import appSettings from "./app.json"
appSettings.version
//           ^?
```

Finally, the following code allows importing non-TypeScript content. There is a .d.ts file which globally says 'md files are OK to import' and 'the module "react" exists, but don't worry about the details'.

Then for a user, they only see the imports and exports inside index.tsx.

ts
ts
import React from "react"
import MultiFileDocs from "./MultiFileDocs.mdx"
 
export default () => <MultiFileDocs/>
ts
import React from "react"
import MultiFileDocs from "./MultiFileDocs.mdx"
 
export default () => <MultiFileDocs/>
md
```ts twoslash
// @filename: ambient.d.ts
declare module '*.mdx' {
    export default any
}
declare module "react"

// @filename: MultiFileDocs.mdx
## Hello world

// @filename: index.tsx
// ---cut---
import React from "react"
import MultiFileDocs from "./MultiFileDocs.mdx"

export default () => <MultiFileDocs/>
```
```ts twoslash
// @filename: ambient.d.ts
declare module '*.mdx' {
    export default any
}
declare module "react"

// @filename: MultiFileDocs.mdx
## Hello world

// @filename: index.tsx
// ---cut---
import React from "react"
import MultiFileDocs from "./MultiFileDocs.mdx"

export default () => <MultiFileDocs/>
```
]]>
Multi-file

Twoslash code examples aren't limited to creating a single file, by using // @filename: [file] you can write any file to the virtual file system used by TypeScript to power your code examples.

@filename: [file]

Most of the time, you don't need to think about the underlaying virtual file system in a code example, but when you have imports between them it becomes important to know. Twoslash will default to creating an index.[type] based on the langauge passed to the code example:

ts
ts
// I'm index.ts
ts
// I'm index.ts
md
```ts twoslash
// I'm index.ts
```
```ts twoslash
// I'm index.ts
```
tsx
tsx
// I'm index.tsx
tsx
// I'm index.tsx
md
```tsx twoslash
// I'm index.tsx
```
```tsx twoslash
// I'm index.tsx
```
js
js
// I'm index.tjs
js
// I'm index.tjs
md
```js twoslash
// I'm index.tjs
```
```js twoslash
// I'm index.tjs
```

Then until Twoslash hits another // @filename: [file], the parser keeps adding new lines into the same file. After seeing @filename Twoslash creates a new virtual file-system file and adds the new lines to that. You can't edit a file after it was created, but you can overwrite it.

It can be any file. For example, if you want to quickly fake a node module:

ts
ts
// @filename: node_modules/@types/mylib/index.d.ts
export function doit(): string
 
// @filename: index.ts
import { doit } from 'mylib'
console.log(doit)
ts
// @filename: node_modules/@types/mylib/index.d.ts
export function doit(): string
 
// @filename: index.ts
import { doit } from 'mylib'
console.log(doit)

This code example sets up the types for a non-existent npm module, and TypeScript picks it up as the definitions in the same way it would in a non-virtual TypeScript project.

md
```ts twoslash
// @filename: node_modules/@types/mylib/index.d.ts
export function doit(): string

// @filename: index.ts
import { doit } from 'mylib'
console.log(doit)
```
```ts twoslash
// @filename: node_modules/@types/mylib/index.d.ts
export function doit(): string

// @filename: index.ts
import { doit } from 'mylib'
console.log(doit)
```

You can also set up a JSON object which can be imported in a TypeScript file:

ts
ts
// @filename: app.json
{ "version": "23.2.3" }
 
// @filename: index.ts
import appSettings from "./app.json"
appSettings.version
(property) "version": string
ts
// @filename: app.json
{ "version": "23.2.3" }
 
// @filename: index.ts
import appSettings from "./app.json"
appSettings.version
(property) "version": string
md
```ts twoslash
// @resolveJsonModule
// @filename: app.json
{ "version": "23.2.3" }

// @filename: index.ts
import appSettings from "./app.json"
appSettings.version
//           ^?
```
```ts twoslash
// @resolveJsonModule
// @filename: app.json
{ "version": "23.2.3" }

// @filename: index.ts
import appSettings from "./app.json"
appSettings.version
//           ^?
```

Finally, the following code allows importing non-TypeScript content. There is a .d.ts file which globally says 'md files are OK to import' and 'the module "react" exists, but don't worry about the details'.

Then for a user, they only see the imports and exports inside index.tsx.

ts
ts
import React from "react"
import MultiFileDocs from "./MultiFileDocs.mdx"
 
export default () => <MultiFileDocs/>
ts
import React from "react"
import MultiFileDocs from "./MultiFileDocs.mdx"
 
export default () => <MultiFileDocs/>
md
```ts twoslash
// @filename: ambient.d.ts
declare module '*.mdx' {
    export default any
}
declare module "react"

// @filename: MultiFileDocs.mdx
## Hello world

// @filename: index.tsx
// ---cut---
import React from "react"
import MultiFileDocs from "./MultiFileDocs.mdx"

export default () => <MultiFileDocs/>
```
```ts twoslash
// @filename: ambient.d.ts
declare module '*.mdx' {
    export default any
}
declare module "react"

// @filename: MultiFileDocs.mdx
## Hello world

// @filename: index.tsx
// ---cut---
import React from "react"
import MultiFileDocs from "./MultiFileDocs.mdx"

export default () => <MultiFileDocs/>
```
]]>
<![CDATA[Queries]]> https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/api/queries https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/api/queries Thu, 01 Jul 2021 00:00:00 GMT Queries

One of the key features of Twoslash is the ability to use the TypeScript compiler to pull out type information about your code. Twoslash comes with two different ways to query your code: ?^ and ?|.

Extract Type ^?

Using ^? you can pull out type information about a particular identifier in the line of code above it.

ts
ts
const hi = 'Hello'
const msg = hi + ', world'
const msg: string
ts
const hi = 'Hello'
const msg = hi + ', world'
const msg: string
md
```ts twoslash
const hi = 'Hello'
const msg = hi + ', world'
//    ^?
```
```ts twoslash
const hi = 'Hello'
const msg = hi + ', world'
//    ^?
```

Completions ^|

Using ^| you can pull out information about a what the auto-complete looks like at a particular location.

ts
ts
console.e
         
ts
console.e
         
md
```ts twoslash
// @noErrors
console.e
//       ^|
```
```ts twoslash
// @noErrors
console.e
//       ^|
```

INFO

Note that the compiler flag for // @noErrors is set, because console.e is a failing TypeScript code sample but we don't really care about that.

]]>
Queries

One of the key features of Twoslash is the ability to use the TypeScript compiler to pull out type information about your code. Twoslash comes with two different ways to query your code: ?^ and ?|.

Extract Type ^?

Using ^? you can pull out type information about a particular identifier in the line of code above it.

ts
ts
const hi = 'Hello'
const msg = hi + ', world'
const msg: string
ts
const hi = 'Hello'
const msg = hi + ', world'
const msg: string
md
```ts twoslash
const hi = 'Hello'
const msg = hi + ', world'
//    ^?
```
```ts twoslash
const hi = 'Hello'
const msg = hi + ', world'
//    ^?
```

Completions ^|

Using ^| you can pull out information about a what the auto-complete looks like at a particular location.

ts
ts
console.e
         
ts
console.e
         
md
```ts twoslash
// @noErrors
console.e
//       ^|
```
```ts twoslash
// @noErrors
console.e
//       ^|
```

INFO

Note that the compiler flag for // @noErrors is set, because console.e is a failing TypeScript code sample but we don't really care about that.

]]>
<![CDATA[@types]]> https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/api/types https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/api/types Thu, 01 Jul 2021 00:00:00 GMT @types

For most examples, you probably need to import external libraries into your code examples.

Twoslash works by faking a virtual file system over your existing file system. This means any @types or libraries with TypeScript definitions should work out of the box with no config.

Local Sources

Simply import locally installed libraries and Twoslash can pick up types:

ts
ts
import { defineConfig } from 'vitepress'
const config = defineConfig({})
const config: UserConfig<DefaultTheme.Config>
export default config
ts
import { defineConfig } from 'vitepress'
const config = defineConfig({})
const config: UserConfig<DefaultTheme.Config>
export default config
md
```ts twoslash
import { defineConfig } from 'vitepress'
const config = defineConfig({})
//    ^?
export default config
```
```ts twoslash
import { defineConfig } from 'vitepress'
const config = defineConfig({})
//    ^?
export default config
```

Globals

Setting up globals is a little bit more complex, but not drastically. You need to use the triple slash reference which adds a particular library to the global scope.

For example, setting up Node imports and globals etc.

ts
ts
import { writeFileSync } from 'fs'
writeFileSync('myfile.txt', '// TODO')
ts
import { writeFileSync } from 'fs'
writeFileSync('myfile.txt', '// TODO')
md
```ts twoslash
/// <reference types="node" />
// ---cut---
import { writeFileSync } from 'fs'
writeFileSync('myfile.txt', '// TODO')
```
```ts twoslash
/// <reference types="node" />
// ---cut---
import { writeFileSync } from 'fs'
writeFileSync('myfile.txt', '// TODO')
```

APIs like Vitest are similar cases where you would use a triple slash reference.

ts
ts
test('my tests', () => {
expect('hello').toEqual('hello')
const expect: ExpectStatic
})
ts
test('my tests', () => {
expect('hello').toEqual('hello')
const expect: ExpectStatic
})
md
```ts twoslash
/// <reference types="vitest/globals" />
// ---cut---

test('my tests', () => {
    expect('hello').toEqual('hello')
    // ^?
})
```
```ts twoslash
/// <reference types="vitest/globals" />
// ---cut---

test('my tests', () => {
    expect('hello').toEqual('hello')
    // ^?
})
```
]]>
@types

For most examples, you probably need to import external libraries into your code examples.

Twoslash works by faking a virtual file system over your existing file system. This means any @types or libraries with TypeScript definitions should work out of the box with no config.

Local Sources

Simply import locally installed libraries and Twoslash can pick up types:

ts
ts
import { defineConfig } from 'vitepress'
const config = defineConfig({})
const config: UserConfig<DefaultTheme.Config>
export default config
ts
import { defineConfig } from 'vitepress'
const config = defineConfig({})
const config: UserConfig<DefaultTheme.Config>
export default config
md
```ts twoslash
import { defineConfig } from 'vitepress'
const config = defineConfig({})
//    ^?
export default config
```
```ts twoslash
import { defineConfig } from 'vitepress'
const config = defineConfig({})
//    ^?
export default config
```

Globals

Setting up globals is a little bit more complex, but not drastically. You need to use the triple slash reference which adds a particular library to the global scope.

For example, setting up Node imports and globals etc.

ts
ts
import { writeFileSync } from 'fs'
writeFileSync('myfile.txt', '// TODO')
ts
import { writeFileSync } from 'fs'
writeFileSync('myfile.txt', '// TODO')
md
```ts twoslash
/// <reference types="node" />
// ---cut---
import { writeFileSync } from 'fs'
writeFileSync('myfile.txt', '// TODO')
```
```ts twoslash
/// <reference types="node" />
// ---cut---
import { writeFileSync } from 'fs'
writeFileSync('myfile.txt', '// TODO')
```

APIs like Vitest are similar cases where you would use a triple slash reference.

ts
ts
test('my tests', () => {
expect('hello').toEqual('hello')
const expect: ExpectStatic
})
ts
test('my tests', () => {
expect('hello').toEqual('hello')
const expect: ExpectStatic
})
md
```ts twoslash
/// <reference types="vitest/globals" />
// ---cut---

test('my tests', () => {
    expect('hello').toEqual('hello')
    // ^?
})
```
```ts twoslash
/// <reference types="vitest/globals" />
// ---cut---

test('my tests', () => {
    expect('hello').toEqual('hello')
    // ^?
})
```
]]>
<![CDATA[Compiler Flags]]> https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/config/flags https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/config/flags Thu, 01 Jul 2021 00:00:00 GMT Compiler Flags
// @allowJs
Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files..

// @allowSyntheticDefaultImports
Allow 'import x from y' when a module doesn't have a default export..

// @allowUmdGlobalAccess
Allow accessing UMD globals from modules..

// @allowUnreachableCode
Disable error reporting for unreachable code..

// @allowUnusedLabels
Disable error reporting for unused labels..

// @alwaysStrict
Ensure 'use strict' is always emitted..

// @assumeChangesOnlyAffectDirectDependencies
Have recompiles in projects that use `incremental` and `watch` mode assume that changes within a file will only affect files directly depending on it..

// @baseUrl
Specify the base directory to resolve non-relative module names..

// @charset
No longer supported. In early versions, manually set the text encoding for reading files..

// @checkJs
Enable error reporting in type-checked JavaScript files..

// @composite
Enable constraints that allow a TypeScript project to be used with project references..

// @declaration
Generate .d.ts files from TypeScript and JavaScript files in your project..

// @declarationDir
Specify the output directory for generated declaration files..

// @declarationMap
Create sourcemaps for d.ts files..

// @diagnostics
Output compiler performance information after building..

// @disableReferencedProjectLoad
Reduce the number of projects loaded automatically by TypeScript..

// @disableSizeLimit
Remove the 20mb cap on total source code size for JavaScript files in the TypeScript language server..

// @disableSolutionSearching
Opt a project out of multi-project reference checking when editing..

// @disableSourceOfProjectReferenceRedirect
Disable preferring source files instead of declaration files when referencing composite projects.

// @downlevelIteration
Emit more compliant, but verbose and less performant JavaScript for iteration..

// @emitBOM
Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files..

// @emitDeclarationOnly
Only output d.ts files and not JavaScript files..

// @emitDecoratorMetadata
Emit design-type metadata for decorated declarations in source files..

// @esModuleInterop
Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility..

// @exactOptionalPropertyTypes
Interpret optional property types as written, rather than adding 'undefined'..

// @experimentalDecorators
Enable experimental support for TC39 stage 2 draft decorators..

// @explainFiles
Print files read during the compilation including why it was included..

// @extendedDiagnostics
Output more detailed compiler performance information after building..

// @forceConsistentCasingInFileNames
Ensure that casing is correct in imports..

// @generateCpuProfile
Emit a v8 CPU profile of the compiler run for debugging..

// @importHelpers
Allow importing helper functions from tslib once per project, instead of including them per-file..

// @importsNotUsedAsValues
Specify emit/checking behavior for imports that are only used for types.

// @incremental
Enable incremental compilation.

// @inlineSourceMap
Include sourcemap files inside the emitted JavaScript..

// @inlineSources
Include source code in the sourcemaps inside the emitted JavaScript..

// @isolatedModules
Ensure that each file can be safely transpiled without relying on other imports..

// @jsx
Specify what JSX code is generated..

// @jsxFactory
Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'.

// @jsxFragmentFactory
Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'..

// @jsxImportSource
Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.`.

// @keyofStringsOnly
Make keyof only return strings instead of string, numbers or symbols. Legacy option..

// @lib
Specify a set of bundled library declaration files that describe the target runtime environment..

// @listEmittedFiles
Print the names of emitted files after a compilation..

// @listFiles
Print all of the files read during the compilation..

// @mapRoot
Specify the location where debugger should locate map files instead of generated locations..

// @maxNodeModuleJsDepth
Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`..

// @module
Specify what module code is generated..

// @moduleResolution
Specify how TypeScript looks up a file from a given module specifier..

// @newLine
Set the newline character for emitting files..

// @noEmit
Disable emitting file from a compilation..

// @noEmitHelpers
Disable generating custom helper functions like `__extends` in compiled output..

// @noEmitOnError
Disable emitting files if any type checking errors are reported..

// @noErrorTruncation
Disable truncating types in error messages..

// @noFallthroughCasesInSwitch
Enable error reporting for fallthrough cases in switch statements..

// @noImplicitAny
Enable error reporting for expressions and declarations with an implied `any` type...

// @noImplicitOverride
Add `undefined` to a type when accessed using an index..

// @noImplicitReturns
Enable error reporting for codepaths that do not explicitly return in a function..

// @noImplicitThis
Enable error reporting when `this` is given the type `any`..

// @noImplicitUseStrict
Disable adding 'use strict' directives in emitted JavaScript files..

// @noLib
Disable including any library files, including the default lib.d.ts..

// @noPropertyAccessFromIndexSignature
Enforces using indexed accessors for keys declared using an indexed type.

// @noResolve
Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project..

// @noStrictGenericChecks
Disable strict checking of generic signatures in function types..

// @noUncheckedIndexedAccess
Include 'undefined' in index signature results.

// @noUnusedLocals
Enable error reporting when a local variables aren't read..

// @noUnusedParameters
Raise an error when a function parameter isn't read.

// @out
Deprecated setting. Use `outFile` instead..

// @outDir
Specify an output folder for all emitted files..

// @outFile
Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output..

// @paths
Specify a set of entries that re-map imports to additional lookup locations..

// @plugins
List of language service plugins..

// @preserveConstEnums
Disable erasing `const enum` declarations in generated code..

// @preserveSymlinks
Disable resolving symlinks to their realpath. This correlates to the same flag in node..

// @preserveWatchOutput
Disable wiping the console in watch mode.

// @pretty
Enable color and formatting in output to make compiler errors easier to read.

// @reactNamespace
Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit..

// @removeComments
Disable emitting comments..

// @resolveJsonModule
Enable importing .json files.

// @rootDir
Specify the root folder within your source files..

// @rootDirs
Allow multiple folders to be treated as one when resolving modules..

// @skipDefaultLibCheck
Skip type checking .d.ts files that are included with TypeScript..

// @skipLibCheck
Skip type checking all .d.ts files..

// @sourceMap
Create source map files for emitted JavaScript files..

// @sourceRoot
Specify the root path for debuggers to find the reference source code..

// @strict
Enable all strict type-checking options..

// @strictBindCallApply
Check that the arguments for `bind`, `call`, and `apply` methods match the original function..

// @strictFunctionTypes
When assigning functions, check to ensure parameters and the return values are subtype-compatible..

// @strictNullChecks
When type checking, take into account `null` and `undefined`..

// @strictPropertyInitialization
Check for class properties that are declared but not set in the constructor..

// @stripInternal
Disable emitting declarations that have `@internal` in their JSDoc comments..

// @suppressExcessPropertyErrors
Disable reporting of excess property errors during the creation of object literals..

// @suppressImplicitAnyIndexErrors
Suppress `noImplicitAny` errors when indexing objects that lack index signatures..

// @target
Set the JavaScript language version for emitted JavaScript and include compatible library declarations..

// @traceResolution
Log paths used during the `moduleResolution` process..

// @tsBuildInfoFile
Specify the folder for .tsbuildinfo incremental compilation files..

// @typeRoots
Specify multiple folders that act like `./node_modules/@types`..

// @types
Specify type package names to be included without being referenced in a source file..

// @useDefineForClassFields
Emit ECMAScript-standard-compliant class fields..

// @useUnknownInCatchVariables
Type catch clause variables as 'unknown' instead of 'any'..
// @allowJs
Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files..

// @allowSyntheticDefaultImports
Allow 'import x from y' when a module doesn't have a default export..

// @allowUmdGlobalAccess
Allow accessing UMD globals from modules..

// @allowUnreachableCode
Disable error reporting for unreachable code..

// @allowUnusedLabels
Disable error reporting for unused labels..

// @alwaysStrict
Ensure 'use strict' is always emitted..

// @assumeChangesOnlyAffectDirectDependencies
Have recompiles in projects that use `incremental` and `watch` mode assume that changes within a file will only affect files directly depending on it..

// @baseUrl
Specify the base directory to resolve non-relative module names..

// @charset
No longer supported. In early versions, manually set the text encoding for reading files..

// @checkJs
Enable error reporting in type-checked JavaScript files..

// @composite
Enable constraints that allow a TypeScript project to be used with project references..

// @declaration
Generate .d.ts files from TypeScript and JavaScript files in your project..

// @declarationDir
Specify the output directory for generated declaration files..

// @declarationMap
Create sourcemaps for d.ts files..

// @diagnostics
Output compiler performance information after building..

// @disableReferencedProjectLoad
Reduce the number of projects loaded automatically by TypeScript..

// @disableSizeLimit
Remove the 20mb cap on total source code size for JavaScript files in the TypeScript language server..

// @disableSolutionSearching
Opt a project out of multi-project reference checking when editing..

// @disableSourceOfProjectReferenceRedirect
Disable preferring source files instead of declaration files when referencing composite projects.

// @downlevelIteration
Emit more compliant, but verbose and less performant JavaScript for iteration..

// @emitBOM
Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files..

// @emitDeclarationOnly
Only output d.ts files and not JavaScript files..

// @emitDecoratorMetadata
Emit design-type metadata for decorated declarations in source files..

// @esModuleInterop
Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility..

// @exactOptionalPropertyTypes
Interpret optional property types as written, rather than adding 'undefined'..

// @experimentalDecorators
Enable experimental support for TC39 stage 2 draft decorators..

// @explainFiles
Print files read during the compilation including why it was included..

// @extendedDiagnostics
Output more detailed compiler performance information after building..

// @forceConsistentCasingInFileNames
Ensure that casing is correct in imports..

// @generateCpuProfile
Emit a v8 CPU profile of the compiler run for debugging..

// @importHelpers
Allow importing helper functions from tslib once per project, instead of including them per-file..

// @importsNotUsedAsValues
Specify emit/checking behavior for imports that are only used for types.

// @incremental
Enable incremental compilation.

// @inlineSourceMap
Include sourcemap files inside the emitted JavaScript..

// @inlineSources
Include source code in the sourcemaps inside the emitted JavaScript..

// @isolatedModules
Ensure that each file can be safely transpiled without relying on other imports..

// @jsx
Specify what JSX code is generated..

// @jsxFactory
Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'.

// @jsxFragmentFactory
Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'..

// @jsxImportSource
Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.`.

// @keyofStringsOnly
Make keyof only return strings instead of string, numbers or symbols. Legacy option..

// @lib
Specify a set of bundled library declaration files that describe the target runtime environment..

// @listEmittedFiles
Print the names of emitted files after a compilation..

// @listFiles
Print all of the files read during the compilation..

// @mapRoot
Specify the location where debugger should locate map files instead of generated locations..

// @maxNodeModuleJsDepth
Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`..

// @module
Specify what module code is generated..

// @moduleResolution
Specify how TypeScript looks up a file from a given module specifier..

// @newLine
Set the newline character for emitting files..

// @noEmit
Disable emitting file from a compilation..

// @noEmitHelpers
Disable generating custom helper functions like `__extends` in compiled output..

// @noEmitOnError
Disable emitting files if any type checking errors are reported..

// @noErrorTruncation
Disable truncating types in error messages..

// @noFallthroughCasesInSwitch
Enable error reporting for fallthrough cases in switch statements..

// @noImplicitAny
Enable error reporting for expressions and declarations with an implied `any` type...

// @noImplicitOverride
Add `undefined` to a type when accessed using an index..

// @noImplicitReturns
Enable error reporting for codepaths that do not explicitly return in a function..

// @noImplicitThis
Enable error reporting when `this` is given the type `any`..

// @noImplicitUseStrict
Disable adding 'use strict' directives in emitted JavaScript files..

// @noLib
Disable including any library files, including the default lib.d.ts..

// @noPropertyAccessFromIndexSignature
Enforces using indexed accessors for keys declared using an indexed type.

// @noResolve
Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project..

// @noStrictGenericChecks
Disable strict checking of generic signatures in function types..

// @noUncheckedIndexedAccess
Include 'undefined' in index signature results.

// @noUnusedLocals
Enable error reporting when a local variables aren't read..

// @noUnusedParameters
Raise an error when a function parameter isn't read.

// @out
Deprecated setting. Use `outFile` instead..

// @outDir
Specify an output folder for all emitted files..

// @outFile
Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output..

// @paths
Specify a set of entries that re-map imports to additional lookup locations..

// @plugins
List of language service plugins..

// @preserveConstEnums
Disable erasing `const enum` declarations in generated code..

// @preserveSymlinks
Disable resolving symlinks to their realpath. This correlates to the same flag in node..

// @preserveWatchOutput
Disable wiping the console in watch mode.

// @pretty
Enable color and formatting in output to make compiler errors easier to read.

// @reactNamespace
Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit..

// @removeComments
Disable emitting comments..

// @resolveJsonModule
Enable importing .json files.

// @rootDir
Specify the root folder within your source files..

// @rootDirs
Allow multiple folders to be treated as one when resolving modules..

// @skipDefaultLibCheck
Skip type checking .d.ts files that are included with TypeScript..

// @skipLibCheck
Skip type checking all .d.ts files..

// @sourceMap
Create source map files for emitted JavaScript files..

// @sourceRoot
Specify the root path for debuggers to find the reference source code..

// @strict
Enable all strict type-checking options..

// @strictBindCallApply
Check that the arguments for `bind`, `call`, and `apply` methods match the original function..

// @strictFunctionTypes
When assigning functions, check to ensure parameters and the return values are subtype-compatible..

// @strictNullChecks
When type checking, take into account `null` and `undefined`..

// @strictPropertyInitialization
Check for class properties that are declared but not set in the constructor..

// @stripInternal
Disable emitting declarations that have `@internal` in their JSDoc comments..

// @suppressExcessPropertyErrors
Disable reporting of excess property errors during the creation of object literals..

// @suppressImplicitAnyIndexErrors
Suppress `noImplicitAny` errors when indexing objects that lack index signatures..

// @target
Set the JavaScript language version for emitted JavaScript and include compatible library declarations..

// @traceResolution
Log paths used during the `moduleResolution` process..

// @tsBuildInfoFile
Specify the folder for .tsbuildinfo incremental compilation files..

// @typeRoots
Specify multiple folders that act like `./node_modules/@types`..

// @types
Specify type package names to be included without being referenced in a source file..

// @useDefineForClassFields
Emit ECMAScript-standard-compliant class fields..

// @useUnknownInCatchVariables
Type catch clause variables as 'unknown' instead of 'any'..
]]>
Compiler Flags
// @allowJs
Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files..

// @allowSyntheticDefaultImports
Allow 'import x from y' when a module doesn't have a default export..

// @allowUmdGlobalAccess
Allow accessing UMD globals from modules..

// @allowUnreachableCode
Disable error reporting for unreachable code..

// @allowUnusedLabels
Disable error reporting for unused labels..

// @alwaysStrict
Ensure 'use strict' is always emitted..

// @assumeChangesOnlyAffectDirectDependencies
Have recompiles in projects that use `incremental` and `watch` mode assume that changes within a file will only affect files directly depending on it..

// @baseUrl
Specify the base directory to resolve non-relative module names..

// @charset
No longer supported. In early versions, manually set the text encoding for reading files..

// @checkJs
Enable error reporting in type-checked JavaScript files..

// @composite
Enable constraints that allow a TypeScript project to be used with project references..

// @declaration
Generate .d.ts files from TypeScript and JavaScript files in your project..

// @declarationDir
Specify the output directory for generated declaration files..

// @declarationMap
Create sourcemaps for d.ts files..

// @diagnostics
Output compiler performance information after building..

// @disableReferencedProjectLoad
Reduce the number of projects loaded automatically by TypeScript..

// @disableSizeLimit
Remove the 20mb cap on total source code size for JavaScript files in the TypeScript language server..

// @disableSolutionSearching
Opt a project out of multi-project reference checking when editing..

// @disableSourceOfProjectReferenceRedirect
Disable preferring source files instead of declaration files when referencing composite projects.

// @downlevelIteration
Emit more compliant, but verbose and less performant JavaScript for iteration..

// @emitBOM
Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files..

// @emitDeclarationOnly
Only output d.ts files and not JavaScript files..

// @emitDecoratorMetadata
Emit design-type metadata for decorated declarations in source files..

// @esModuleInterop
Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility..

// @exactOptionalPropertyTypes
Interpret optional property types as written, rather than adding 'undefined'..

// @experimentalDecorators
Enable experimental support for TC39 stage 2 draft decorators..

// @explainFiles
Print files read during the compilation including why it was included..

// @extendedDiagnostics
Output more detailed compiler performance information after building..

// @forceConsistentCasingInFileNames
Ensure that casing is correct in imports..

// @generateCpuProfile
Emit a v8 CPU profile of the compiler run for debugging..

// @importHelpers
Allow importing helper functions from tslib once per project, instead of including them per-file..

// @importsNotUsedAsValues
Specify emit/checking behavior for imports that are only used for types.

// @incremental
Enable incremental compilation.

// @inlineSourceMap
Include sourcemap files inside the emitted JavaScript..

// @inlineSources
Include source code in the sourcemaps inside the emitted JavaScript..

// @isolatedModules
Ensure that each file can be safely transpiled without relying on other imports..

// @jsx
Specify what JSX code is generated..

// @jsxFactory
Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'.

// @jsxFragmentFactory
Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'..

// @jsxImportSource
Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.`.

// @keyofStringsOnly
Make keyof only return strings instead of string, numbers or symbols. Legacy option..

// @lib
Specify a set of bundled library declaration files that describe the target runtime environment..

// @listEmittedFiles
Print the names of emitted files after a compilation..

// @listFiles
Print all of the files read during the compilation..

// @mapRoot
Specify the location where debugger should locate map files instead of generated locations..

// @maxNodeModuleJsDepth
Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`..

// @module
Specify what module code is generated..

// @moduleResolution
Specify how TypeScript looks up a file from a given module specifier..

// @newLine
Set the newline character for emitting files..

// @noEmit
Disable emitting file from a compilation..

// @noEmitHelpers
Disable generating custom helper functions like `__extends` in compiled output..

// @noEmitOnError
Disable emitting files if any type checking errors are reported..

// @noErrorTruncation
Disable truncating types in error messages..

// @noFallthroughCasesInSwitch
Enable error reporting for fallthrough cases in switch statements..

// @noImplicitAny
Enable error reporting for expressions and declarations with an implied `any` type...

// @noImplicitOverride
Add `undefined` to a type when accessed using an index..

// @noImplicitReturns
Enable error reporting for codepaths that do not explicitly return in a function..

// @noImplicitThis
Enable error reporting when `this` is given the type `any`..

// @noImplicitUseStrict
Disable adding 'use strict' directives in emitted JavaScript files..

// @noLib
Disable including any library files, including the default lib.d.ts..

// @noPropertyAccessFromIndexSignature
Enforces using indexed accessors for keys declared using an indexed type.

// @noResolve
Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project..

// @noStrictGenericChecks
Disable strict checking of generic signatures in function types..

// @noUncheckedIndexedAccess
Include 'undefined' in index signature results.

// @noUnusedLocals
Enable error reporting when a local variables aren't read..

// @noUnusedParameters
Raise an error when a function parameter isn't read.

// @out
Deprecated setting. Use `outFile` instead..

// @outDir
Specify an output folder for all emitted files..

// @outFile
Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output..

// @paths
Specify a set of entries that re-map imports to additional lookup locations..

// @plugins
List of language service plugins..

// @preserveConstEnums
Disable erasing `const enum` declarations in generated code..

// @preserveSymlinks
Disable resolving symlinks to their realpath. This correlates to the same flag in node..

// @preserveWatchOutput
Disable wiping the console in watch mode.

// @pretty
Enable color and formatting in output to make compiler errors easier to read.

// @reactNamespace
Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit..

// @removeComments
Disable emitting comments..

// @resolveJsonModule
Enable importing .json files.

// @rootDir
Specify the root folder within your source files..

// @rootDirs
Allow multiple folders to be treated as one when resolving modules..

// @skipDefaultLibCheck
Skip type checking .d.ts files that are included with TypeScript..

// @skipLibCheck
Skip type checking all .d.ts files..

// @sourceMap
Create source map files for emitted JavaScript files..

// @sourceRoot
Specify the root path for debuggers to find the reference source code..

// @strict
Enable all strict type-checking options..

// @strictBindCallApply
Check that the arguments for `bind`, `call`, and `apply` methods match the original function..

// @strictFunctionTypes
When assigning functions, check to ensure parameters and the return values are subtype-compatible..

// @strictNullChecks
When type checking, take into account `null` and `undefined`..

// @strictPropertyInitialization
Check for class properties that are declared but not set in the constructor..

// @stripInternal
Disable emitting declarations that have `@internal` in their JSDoc comments..

// @suppressExcessPropertyErrors
Disable reporting of excess property errors during the creation of object literals..

// @suppressImplicitAnyIndexErrors
Suppress `noImplicitAny` errors when indexing objects that lack index signatures..

// @target
Set the JavaScript language version for emitted JavaScript and include compatible library declarations..

// @traceResolution
Log paths used during the `moduleResolution` process..

// @tsBuildInfoFile
Specify the folder for .tsbuildinfo incremental compilation files..

// @typeRoots
Specify multiple folders that act like `./node_modules/@types`..

// @types
Specify type package names to be included without being referenced in a source file..

// @useDefineForClassFields
Emit ECMAScript-standard-compliant class fields..

// @useUnknownInCatchVariables
Type catch clause variables as 'unknown' instead of 'any'..
// @allowJs
Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files..

// @allowSyntheticDefaultImports
Allow 'import x from y' when a module doesn't have a default export..

// @allowUmdGlobalAccess
Allow accessing UMD globals from modules..

// @allowUnreachableCode
Disable error reporting for unreachable code..

// @allowUnusedLabels
Disable error reporting for unused labels..

// @alwaysStrict
Ensure 'use strict' is always emitted..

// @assumeChangesOnlyAffectDirectDependencies
Have recompiles in projects that use `incremental` and `watch` mode assume that changes within a file will only affect files directly depending on it..

// @baseUrl
Specify the base directory to resolve non-relative module names..

// @charset
No longer supported. In early versions, manually set the text encoding for reading files..

// @checkJs
Enable error reporting in type-checked JavaScript files..

// @composite
Enable constraints that allow a TypeScript project to be used with project references..

// @declaration
Generate .d.ts files from TypeScript and JavaScript files in your project..

// @declarationDir
Specify the output directory for generated declaration files..

// @declarationMap
Create sourcemaps for d.ts files..

// @diagnostics
Output compiler performance information after building..

// @disableReferencedProjectLoad
Reduce the number of projects loaded automatically by TypeScript..

// @disableSizeLimit
Remove the 20mb cap on total source code size for JavaScript files in the TypeScript language server..

// @disableSolutionSearching
Opt a project out of multi-project reference checking when editing..

// @disableSourceOfProjectReferenceRedirect
Disable preferring source files instead of declaration files when referencing composite projects.

// @downlevelIteration
Emit more compliant, but verbose and less performant JavaScript for iteration..

// @emitBOM
Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files..

// @emitDeclarationOnly
Only output d.ts files and not JavaScript files..

// @emitDecoratorMetadata
Emit design-type metadata for decorated declarations in source files..

// @esModuleInterop
Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility..

// @exactOptionalPropertyTypes
Interpret optional property types as written, rather than adding 'undefined'..

// @experimentalDecorators
Enable experimental support for TC39 stage 2 draft decorators..

// @explainFiles
Print files read during the compilation including why it was included..

// @extendedDiagnostics
Output more detailed compiler performance information after building..

// @forceConsistentCasingInFileNames
Ensure that casing is correct in imports..

// @generateCpuProfile
Emit a v8 CPU profile of the compiler run for debugging..

// @importHelpers
Allow importing helper functions from tslib once per project, instead of including them per-file..

// @importsNotUsedAsValues
Specify emit/checking behavior for imports that are only used for types.

// @incremental
Enable incremental compilation.

// @inlineSourceMap
Include sourcemap files inside the emitted JavaScript..

// @inlineSources
Include source code in the sourcemaps inside the emitted JavaScript..

// @isolatedModules
Ensure that each file can be safely transpiled without relying on other imports..

// @jsx
Specify what JSX code is generated..

// @jsxFactory
Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'.

// @jsxFragmentFactory
Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'..

// @jsxImportSource
Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.`.

// @keyofStringsOnly
Make keyof only return strings instead of string, numbers or symbols. Legacy option..

// @lib
Specify a set of bundled library declaration files that describe the target runtime environment..

// @listEmittedFiles
Print the names of emitted files after a compilation..

// @listFiles
Print all of the files read during the compilation..

// @mapRoot
Specify the location where debugger should locate map files instead of generated locations..

// @maxNodeModuleJsDepth
Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`..

// @module
Specify what module code is generated..

// @moduleResolution
Specify how TypeScript looks up a file from a given module specifier..

// @newLine
Set the newline character for emitting files..

// @noEmit
Disable emitting file from a compilation..

// @noEmitHelpers
Disable generating custom helper functions like `__extends` in compiled output..

// @noEmitOnError
Disable emitting files if any type checking errors are reported..

// @noErrorTruncation
Disable truncating types in error messages..

// @noFallthroughCasesInSwitch
Enable error reporting for fallthrough cases in switch statements..

// @noImplicitAny
Enable error reporting for expressions and declarations with an implied `any` type...

// @noImplicitOverride
Add `undefined` to a type when accessed using an index..

// @noImplicitReturns
Enable error reporting for codepaths that do not explicitly return in a function..

// @noImplicitThis
Enable error reporting when `this` is given the type `any`..

// @noImplicitUseStrict
Disable adding 'use strict' directives in emitted JavaScript files..

// @noLib
Disable including any library files, including the default lib.d.ts..

// @noPropertyAccessFromIndexSignature
Enforces using indexed accessors for keys declared using an indexed type.

// @noResolve
Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project..

// @noStrictGenericChecks
Disable strict checking of generic signatures in function types..

// @noUncheckedIndexedAccess
Include 'undefined' in index signature results.

// @noUnusedLocals
Enable error reporting when a local variables aren't read..

// @noUnusedParameters
Raise an error when a function parameter isn't read.

// @out
Deprecated setting. Use `outFile` instead..

// @outDir
Specify an output folder for all emitted files..

// @outFile
Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output..

// @paths
Specify a set of entries that re-map imports to additional lookup locations..

// @plugins
List of language service plugins..

// @preserveConstEnums
Disable erasing `const enum` declarations in generated code..

// @preserveSymlinks
Disable resolving symlinks to their realpath. This correlates to the same flag in node..

// @preserveWatchOutput
Disable wiping the console in watch mode.

// @pretty
Enable color and formatting in output to make compiler errors easier to read.

// @reactNamespace
Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit..

// @removeComments
Disable emitting comments..

// @resolveJsonModule
Enable importing .json files.

// @rootDir
Specify the root folder within your source files..

// @rootDirs
Allow multiple folders to be treated as one when resolving modules..

// @skipDefaultLibCheck
Skip type checking .d.ts files that are included with TypeScript..

// @skipLibCheck
Skip type checking all .d.ts files..

// @sourceMap
Create source map files for emitted JavaScript files..

// @sourceRoot
Specify the root path for debuggers to find the reference source code..

// @strict
Enable all strict type-checking options..

// @strictBindCallApply
Check that the arguments for `bind`, `call`, and `apply` methods match the original function..

// @strictFunctionTypes
When assigning functions, check to ensure parameters and the return values are subtype-compatible..

// @strictNullChecks
When type checking, take into account `null` and `undefined`..

// @strictPropertyInitialization
Check for class properties that are declared but not set in the constructor..

// @stripInternal
Disable emitting declarations that have `@internal` in their JSDoc comments..

// @suppressExcessPropertyErrors
Disable reporting of excess property errors during the creation of object literals..

// @suppressImplicitAnyIndexErrors
Suppress `noImplicitAny` errors when indexing objects that lack index signatures..

// @target
Set the JavaScript language version for emitted JavaScript and include compatible library declarations..

// @traceResolution
Log paths used during the `moduleResolution` process..

// @tsBuildInfoFile
Specify the folder for .tsbuildinfo incremental compilation files..

// @typeRoots
Specify multiple folders that act like `./node_modules/@types`..

// @types
Specify type package names to be included without being referenced in a source file..

// @useDefineForClassFields
Emit ECMAScript-standard-compliant class fields..

// @useUnknownInCatchVariables
Type catch clause variables as 'unknown' instead of 'any'..
]]>
<![CDATA[Config]]> https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/config/reference https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/config/reference Thu, 01 Jul 2021 00:00:00 GMT Config

Overview

You can configure VitePress Twoslash using the twoslash property added to defineConfig.

ts
ts
// .vitepress/config.[ext]
import { defineConfig } from 'vitepress'
import { withTwoslash, TwoslashConfigSettings } from '@andatoshiki/vitepress-plugin-shiki-twoslash'
 
export default withTwoslash(
defineConfig({
twoslash: {
// Your VitePress Twoslash options
},
})
)
ts
// .vitepress/config.[ext]
import { defineConfig } from 'vitepress'
import { withTwoslash, TwoslashConfigSettings } from '@andatoshiki/vitepress-plugin-shiki-twoslash'
 
export default withTwoslash(
defineConfig({
twoslash: {
// Your VitePress Twoslash options
},
})
)

INFO

In addition to the below config options, VitePress Twoslash also supports all shiki HighlighterOptions and @typescript/twoslash TwoSlashOptions.

Options

addTryButton

A way to turn on the try buttons seen on the TS website.

  • Type: boolean
  • Default: false
ts
export default withTwoslash(
    defineConfig({
        twoslash: {
            addTryButton: true, 
        },
    })
)
export default withTwoslash(
    defineConfig({
        twoslash: {
            addTryButton: true, 
        },
    })
)

alwayRaiseForTwoslashExceptions

Instead of showing twoslash exceptions inline, throw the entire process like it will on CI.

  • Type: boolean
  • Default: false
ts
export default withTwoslash(
    defineConfig({
        twoslash: {
            alwayRaiseForTwoslashExceptions: true, 
        },
    })
)
export default withTwoslash(
    defineConfig({
        twoslash: {
            alwayRaiseForTwoslashExceptions: true, 
        },
    })
)

disableImplicitReactImport

A way to disable implicit React imports on tsx/jsx language codeblocks

  • Type: boolean
  • Default: false
ts
export default withTwoslash(
    defineConfig({
        twoslash: {
            disableImplicitReactImport: true, 
        },
    })
)
export default withTwoslash(
    defineConfig({
        twoslash: {
            disableImplicitReactImport: true, 
        },
    })
)

includeJSDocInHover

Include JSDoc comments in the hovers.

  • Type: boolean
  • Default: false
ts
export default withTwoslash(
    defineConfig({
        twoslash: {
            includeJSDocInHover: true, 
        },
    })
)
export default withTwoslash(
    defineConfig({
        twoslash: {
            includeJSDocInHover: true, 
        },
    })
)

ignoreCodeblocksWithCodefenceMeta

Ignore transforming certain code blocks.

  • Type: boolean
  • Default: false
ts
export default withTwoslash(
    defineConfig({
        twoslash: {
            ignoreCodeblocksWithCodefenceMeta: true, 
        },
    })
)
export default withTwoslash(
    defineConfig({
        twoslash: {
            ignoreCodeblocksWithCodefenceMeta: true, 
        },
    })
)

wrapFragments

A way to add a div wrapper for multi-theme outputs.

  • Type: boolean
  • Default: false
ts
export default withTwoslash(
    defineConfig({
        twoslash: {
            wrapFragments: true, 
        },
    })
)
export default withTwoslash(
    defineConfig({
        twoslash: {
            wrapFragments: true, 
        },
    })
)
]]>
Config

Overview

You can configure VitePress Twoslash using the twoslash property added to defineConfig.

ts
ts
// .vitepress/config.[ext]
import { defineConfig } from 'vitepress'
import { withTwoslash, TwoslashConfigSettings } from '@andatoshiki/vitepress-plugin-shiki-twoslash'
 
export default withTwoslash(
defineConfig({
twoslash: {
// Your VitePress Twoslash options
},
})
)
ts
// .vitepress/config.[ext]
import { defineConfig } from 'vitepress'
import { withTwoslash, TwoslashConfigSettings } from '@andatoshiki/vitepress-plugin-shiki-twoslash'
 
export default withTwoslash(
defineConfig({
twoslash: {
// Your VitePress Twoslash options
},
})
)

INFO

In addition to the below config options, VitePress Twoslash also supports all shiki HighlighterOptions and @typescript/twoslash TwoSlashOptions.

Options

addTryButton

A way to turn on the try buttons seen on the TS website.

  • Type: boolean
  • Default: false
ts
export default withTwoslash(
    defineConfig({
        twoslash: {
            addTryButton: true, 
        },
    })
)
export default withTwoslash(
    defineConfig({
        twoslash: {
            addTryButton: true, 
        },
    })
)

alwayRaiseForTwoslashExceptions

Instead of showing twoslash exceptions inline, throw the entire process like it will on CI.

  • Type: boolean
  • Default: false
ts
export default withTwoslash(
    defineConfig({
        twoslash: {
            alwayRaiseForTwoslashExceptions: true, 
        },
    })
)
export default withTwoslash(
    defineConfig({
        twoslash: {
            alwayRaiseForTwoslashExceptions: true, 
        },
    })
)

disableImplicitReactImport

A way to disable implicit React imports on tsx/jsx language codeblocks

  • Type: boolean
  • Default: false
ts
export default withTwoslash(
    defineConfig({
        twoslash: {
            disableImplicitReactImport: true, 
        },
    })
)
export default withTwoslash(
    defineConfig({
        twoslash: {
            disableImplicitReactImport: true, 
        },
    })
)

includeJSDocInHover

Include JSDoc comments in the hovers.

  • Type: boolean
  • Default: false
ts
export default withTwoslash(
    defineConfig({
        twoslash: {
            includeJSDocInHover: true, 
        },
    })
)
export default withTwoslash(
    defineConfig({
        twoslash: {
            includeJSDocInHover: true, 
        },
    })
)

ignoreCodeblocksWithCodefenceMeta

Ignore transforming certain code blocks.

  • Type: boolean
  • Default: false
ts
export default withTwoslash(
    defineConfig({
        twoslash: {
            ignoreCodeblocksWithCodefenceMeta: true, 
        },
    })
)
export default withTwoslash(
    defineConfig({
        twoslash: {
            ignoreCodeblocksWithCodefenceMeta: true, 
        },
    })
)

wrapFragments

A way to add a div wrapper for multi-theme outputs.

  • Type: boolean
  • Default: false
ts
export default withTwoslash(
    defineConfig({
        twoslash: {
            wrapFragments: true, 
        },
    })
)
export default withTwoslash(
    defineConfig({
        twoslash: {
            wrapFragments: true, 
        },
    })
)
]]>
<![CDATA[Using a Custom Theme]]> https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/guide/custom-theme https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/guide/custom-theme Thu, 01 Jul 2021 00:00:00 GMT Using a Custom Theme

Twoslash uses your markdown.theme for syntax highlighting, but there are a few other things you can do to customize the look and feel of your code examples — particulary the generated Twoslash interface.

CSS Variables

The following CSS variables (and their defaults) are available to style Twoslash interface:

css
:root {
    --vp-twoslash-c-annotation-fg: var(--vp-c-text-1);

    --vp-twoslash-c-brand: var(--vp-c-brand);

    --vp-twoslash-c-error-bg: var(--vp-c-red-dimm-2);
    --vp-twoslash-c-error-fg: var(--vp-c-text-1);

    --vp-twoslash-c-logger-error-bg: var(--vp-c-red-dimm-2);
    --vp-twoslash-c-logger-error-fg: var(--vp-c-red-dark);
    --vp-twoslash-c-logger-fg: var(--vp-c-text-1);
    --vp-twoslash-c-logger-log-bg: var(--vp-c-mute-dark);
    --vp-twoslash-c-logger-log-fg: var(--vp-c-gray);
    --vp-twoslash-c-logger-warn-bg: var(--vp-c-yellow-dimm-2);
    --vp-twoslash-c-logger-warn-fg: var(--vp-c-yellow-dark);

    --vp-twoslash-c-lsp-bg: var(--vp-c-bg-elv);
    --vp-twoslash-c-lsp-border: var(--vp-c-divider);
    --vp-twoslash-c-lsp-fg: var(--vp-c-text-1);
    --vp-twoslash-c-lsp-underline: var(--vp-c-text-2);
    --vp-twoslash-lsp-shadow: var(--vp-shadow-2);

    --vp-twoslash-c-query-bg: var(--vp-c-mute-darker);
    --vp-twoslash-c-query-fg-2: var(--vp-c-text-2);
    --vp-twoslash-c-query-fg: var(--vp-c-text-1);
}
:root {
    --vp-twoslash-c-annotation-fg: var(--vp-c-text-1);

    --vp-twoslash-c-brand: var(--vp-c-brand);

    --vp-twoslash-c-error-bg: var(--vp-c-red-dimm-2);
    --vp-twoslash-c-error-fg: var(--vp-c-text-1);

    --vp-twoslash-c-logger-error-bg: var(--vp-c-red-dimm-2);
    --vp-twoslash-c-logger-error-fg: var(--vp-c-red-dark);
    --vp-twoslash-c-logger-fg: var(--vp-c-text-1);
    --vp-twoslash-c-logger-log-bg: var(--vp-c-mute-dark);
    --vp-twoslash-c-logger-log-fg: var(--vp-c-gray);
    --vp-twoslash-c-logger-warn-bg: var(--vp-c-yellow-dimm-2);
    --vp-twoslash-c-logger-warn-fg: var(--vp-c-yellow-dark);

    --vp-twoslash-c-lsp-bg: var(--vp-c-bg-elv);
    --vp-twoslash-c-lsp-border: var(--vp-c-divider);
    --vp-twoslash-c-lsp-fg: var(--vp-c-text-1);
    --vp-twoslash-c-lsp-underline: var(--vp-c-text-2);
    --vp-twoslash-lsp-shadow: var(--vp-shadow-2);

    --vp-twoslash-c-query-bg: var(--vp-c-mute-darker);
    --vp-twoslash-c-query-fg-2: var(--vp-c-text-2);
    --vp-twoslash-c-query-fg: var(--vp-c-text-1);
}

Dark/Light Theme

If you pass a responsive theme to markdown.theme, you probably also want to hide/show the correct theme based on the user's settings.

ts
ts
export default defineConfig({
markdown: {
theme: { dark: 'vitesse-dark', light: 'vitesse-light' },
},
})
ts
export default defineConfig({
markdown: {
theme: { dark: 'vitesse-dark', light: 'vitesse-light' },
},
})

You can do this with the following CSS:

css
/*
 * Hide block based on theme
 * `[class*='-dark']` matches `'vitesse-dark'`
 * `[class*='-light']` matches `'vitesse-light'`
 */
html:not(.dark) pre.shiki[class*='-dark'] {
    display: none;
}
html:not(.dark) pre.shiki[class*='-light'] {
    display: block;
}
html.dark pre.shiki[class*='-dark'] {
    display: block;
}
html.dark pre.shiki[class*='-light'] {
    display: none;
}
/*
 * Hide block based on theme
 * `[class*='-dark']` matches `'vitesse-dark'`
 * `[class*='-light']` matches `'vitesse-light'`
 */
html:not(.dark) pre.shiki[class*='-dark'] {
    display: none;
}
html:not(.dark) pre.shiki[class*='-light'] {
    display: block;
}
html.dark pre.shiki[class*='-dark'] {
    display: block;
}
html.dark pre.shiki[class*='-light'] {
    display: none;
}
]]>
Using a Custom Theme

Twoslash uses your markdown.theme for syntax highlighting, but there are a few other things you can do to customize the look and feel of your code examples — particulary the generated Twoslash interface.

CSS Variables

The following CSS variables (and their defaults) are available to style Twoslash interface:

css
:root {
    --vp-twoslash-c-annotation-fg: var(--vp-c-text-1);

    --vp-twoslash-c-brand: var(--vp-c-brand);

    --vp-twoslash-c-error-bg: var(--vp-c-red-dimm-2);
    --vp-twoslash-c-error-fg: var(--vp-c-text-1);

    --vp-twoslash-c-logger-error-bg: var(--vp-c-red-dimm-2);
    --vp-twoslash-c-logger-error-fg: var(--vp-c-red-dark);
    --vp-twoslash-c-logger-fg: var(--vp-c-text-1);
    --vp-twoslash-c-logger-log-bg: var(--vp-c-mute-dark);
    --vp-twoslash-c-logger-log-fg: var(--vp-c-gray);
    --vp-twoslash-c-logger-warn-bg: var(--vp-c-yellow-dimm-2);
    --vp-twoslash-c-logger-warn-fg: var(--vp-c-yellow-dark);

    --vp-twoslash-c-lsp-bg: var(--vp-c-bg-elv);
    --vp-twoslash-c-lsp-border: var(--vp-c-divider);
    --vp-twoslash-c-lsp-fg: var(--vp-c-text-1);
    --vp-twoslash-c-lsp-underline: var(--vp-c-text-2);
    --vp-twoslash-lsp-shadow: var(--vp-shadow-2);

    --vp-twoslash-c-query-bg: var(--vp-c-mute-darker);
    --vp-twoslash-c-query-fg-2: var(--vp-c-text-2);
    --vp-twoslash-c-query-fg: var(--vp-c-text-1);
}
:root {
    --vp-twoslash-c-annotation-fg: var(--vp-c-text-1);

    --vp-twoslash-c-brand: var(--vp-c-brand);

    --vp-twoslash-c-error-bg: var(--vp-c-red-dimm-2);
    --vp-twoslash-c-error-fg: var(--vp-c-text-1);

    --vp-twoslash-c-logger-error-bg: var(--vp-c-red-dimm-2);
    --vp-twoslash-c-logger-error-fg: var(--vp-c-red-dark);
    --vp-twoslash-c-logger-fg: var(--vp-c-text-1);
    --vp-twoslash-c-logger-log-bg: var(--vp-c-mute-dark);
    --vp-twoslash-c-logger-log-fg: var(--vp-c-gray);
    --vp-twoslash-c-logger-warn-bg: var(--vp-c-yellow-dimm-2);
    --vp-twoslash-c-logger-warn-fg: var(--vp-c-yellow-dark);

    --vp-twoslash-c-lsp-bg: var(--vp-c-bg-elv);
    --vp-twoslash-c-lsp-border: var(--vp-c-divider);
    --vp-twoslash-c-lsp-fg: var(--vp-c-text-1);
    --vp-twoslash-c-lsp-underline: var(--vp-c-text-2);
    --vp-twoslash-lsp-shadow: var(--vp-shadow-2);

    --vp-twoslash-c-query-bg: var(--vp-c-mute-darker);
    --vp-twoslash-c-query-fg-2: var(--vp-c-text-2);
    --vp-twoslash-c-query-fg: var(--vp-c-text-1);
}

Dark/Light Theme

If you pass a responsive theme to markdown.theme, you probably also want to hide/show the correct theme based on the user's settings.

ts
ts
export default defineConfig({
markdown: {
theme: { dark: 'vitesse-dark', light: 'vitesse-light' },
},
})
ts
export default defineConfig({
markdown: {
theme: { dark: 'vitesse-dark', light: 'vitesse-light' },
},
})

You can do this with the following CSS:

css
/*
 * Hide block based on theme
 * `[class*='-dark']` matches `'vitesse-dark'`
 * `[class*='-light']` matches `'vitesse-light'`
 */
html:not(.dark) pre.shiki[class*='-dark'] {
    display: none;
}
html:not(.dark) pre.shiki[class*='-light'] {
    display: block;
}
html.dark pre.shiki[class*='-dark'] {
    display: block;
}
html.dark pre.shiki[class*='-light'] {
    display: none;
}
/*
 * Hide block based on theme
 * `[class*='-dark']` matches `'vitesse-dark'`
 * `[class*='-light']` matches `'vitesse-light'`
 */
html:not(.dark) pre.shiki[class*='-dark'] {
    display: none;
}
html:not(.dark) pre.shiki[class*='-light'] {
    display: block;
}
html.dark pre.shiki[class*='-dark'] {
    display: block;
}
html.dark pre.shiki[class*='-light'] {
    display: none;
}
]]>
<![CDATA[Markdown Extensions]]> https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/guide/markdown-extensions https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/guide/markdown-extensions Thu, 01 Jul 2021 00:00:00 GMT Markdown Extensions

Code Groups

Code Groups and Twoslash multi-file support.

ts
ts
import { name } from './name'
export function hello(name: string) {
console.log(`Hello, ${name}!`)
}
hello(name)
(alias) const name: "twoslash" import name
ts
import { name } from './name'
export function hello(name: string) {
console.log(`Hello, ${name}!`)
}
hello(name)
(alias) const name: "twoslash" import name
ts
ts
export const name = 'twoslash'
ts
export const name = 'twoslash'

Unsupported Extensions

Since VitePress Twoslash uses it's own Shiki highlighter, the following syntax highlighting extensions are not currently compatible.

If you are interested in adding support, please start a new GitHub Discussion.

]]>
Markdown Extensions

Code Groups

Code Groups and Twoslash multi-file support.

ts
ts
import { name } from './name'
export function hello(name: string) {
console.log(`Hello, ${name}!`)
}
hello(name)
(alias) const name: "twoslash" import name
ts
import { name } from './name'
export function hello(name: string) {
console.log(`Hello, ${name}!`)
}
hello(name)
(alias) const name: "twoslash" import name
ts
ts
export const name = 'twoslash'
ts
export const name = 'twoslash'

Unsupported Extensions

Since VitePress Twoslash uses it's own Shiki highlighter, the following syntax highlighting extensions are not currently compatible.

If you are interested in adding support, please start a new GitHub Discussion.

]]>
<![CDATA[VitePress Twoslash: VitePress Plugin for Shiki Twoslash]]> https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/ https://note.toshiki.dev/application/vitepress-plugin-shiki-twoslash/ Thu, 01 Jul 2021 00:00:00 GMT @andatoshiki/vitepress-plugin-shiki-twoslash

Static code examples for VitePress using Shiki Twoslash — powered by the syntax engine of Visual Studio Code and the TypeScript compiler.

Overview

Try moving your cursor into the code block below:

ts
ts
// Removes 'readonly' attributes from a type's properties
type CreateMutable<Type> = {
-readonly [Property in keyof Type]: Type[Property]
}
 
type LockedAccount = {
readonly id: string
readonly name: string
}
 
type UnlockedAccount = CreateMutable<LockedAccount>
ts
// Removes 'readonly' attributes from a type's properties
type CreateMutable<Type> = {
-readonly [Property in keyof Type]: Type[Property]
}
 
type LockedAccount = {
readonly id: string
readonly name: string
}
 
type UnlockedAccount = CreateMutable<LockedAccount>

Pretty neat, right? To some extent, anything your editor can show you about code, Twoslash can show. For example, here is the real auto-complete for a VitePress config:

ts
ts
import { defineConfig } from 'vitepress'
 
export default defineConfig({
ti,
      
})
ts
import { defineConfig } from 'vitepress'
 
export default defineConfig({
ti,
      
})

The name Twoslash refers to specially formatted comments (e.g. // ^?) which can be used to set up your environment, like compiler flags or separate input files. It couldn't be easier to set up and start creating incredible code examples!

Install

Install @andatoshiki/vitepress-plugin-shiki-twoslash (requires vitepress@>=1.0.0-alpha.61).

bash
pnpm add @andatoshiki/vitepress-plugin-shiki-twoslash
pnpm add @andatoshiki/vitepress-plugin-shiki-twoslash
bash
npm i @andatoshiki/vitepress-plugin-shiki-twoslash
npm i @andatoshiki/vitepress-plugin-shiki-twoslash
bash
yarn add @andatoshiki/vitepress-plugin-shiki-twoslash
yarn add @andatoshiki/vitepress-plugin-shiki-twoslash

WARNING

Until shiki-twoslash uses the same version of shiki as VitePress, you must override the following packages' shiki versions for syntax highlighting to look the same.

json
{
    "pnpm": {
        "overrides": {
            "remark-shiki-twoslash>shiki": "^0.14.1",
            "shiki-twoslash>shiki": "^0.14.1"
        }
    }
}
{
    "pnpm": {
        "overrides": {
            "remark-shiki-twoslash>shiki": "^0.14.1",
            "shiki-twoslash>shiki": "^0.14.1"
        }
    }
}

Tracked in an upstream issue: https://github.com/shikijs/twoslash/issues/180

Configure

First, wrap your VitePress config file with the withTwoslash wrapper.

ts
ts
// .vitepress/config.[ext]
import { defineConfig } from 'vitepress'
import { withTwoslash } from '@andatoshiki/vitepress-plugin-shiki-twoslash'
 
export default withTwoslash(
defineConfig({
// Your VitePress config
})
)
ts
// .vitepress/config.[ext]
import { defineConfig } from 'vitepress'
import { withTwoslash } from '@andatoshiki/vitepress-plugin-shiki-twoslash'
 
export default withTwoslash(
defineConfig({
// Your VitePress config
})
)

Then, import @andatoshiki/vitepress-plugin-shiki-twoslash/styles.css into your theme.

ts
ts
// .vitepress/theme/index.ts
import defaultTheme from 'vitepress/theme'
import '@andatoshiki/vitepress-plugin-shiki-twoslash/styles.css'
 
export default defaultTheme
ts
// .vitepress/theme/index.ts
import defaultTheme from 'vitepress/theme'
import '@andatoshiki/vitepress-plugin-shiki-twoslash/styles.css'
 
export default defaultTheme

TIP

You can configure VitePress Twoslash using the twoslash property added to defineConfig.

Add Twoslash

Finally, add the twoslash attribute to markdown fenced code blocks.

md
```ts twoslash
// Removes 'readonly' attributes from a type's properties
type CreateMutable<Type> = {
    -readonly [Property in keyof Type]: Type[Property]
}

type LockedAccount = {
    readonly id: string
    readonly name: string
}

type UnlockedAccount = CreateMutable<LockedAccount>
//   ^?
```
```ts twoslash
// Removes 'readonly' attributes from a type's properties
type CreateMutable<Type> = {
    -readonly [Property in keyof Type]: Type[Property]
}

type LockedAccount = {
    readonly id: string
    readonly name: string
}

type UnlockedAccount = CreateMutable<LockedAccount>
//   ^?
```

And your code blocks will be twoslashified!

ts
ts
// Removes 'readonly' attributes from a type's properties
type CreateMutable<Type> = {
-readonly [Property in keyof Type]: Type[Property]
}
 
type LockedAccount = {
readonly id: string
readonly name: string
}
 
type UnlockedAccount = CreateMutable<LockedAccount>
type UnlockedAccount = { id: string; name: string; }
ts
// Removes 'readonly' attributes from a type's properties
type CreateMutable<Type> = {
-readonly [Property in keyof Type]: Type[Property]
}
 
type LockedAccount = {
readonly id: string
readonly name: string
}
 
type UnlockedAccount = CreateMutable<LockedAccount>
type UnlockedAccount = { id: string; name: string; }
]]>
@andatoshiki/vitepress-plugin-shiki-twoslash

Static code examples for VitePress using Shiki Twoslash — powered by the syntax engine of Visual Studio Code and the TypeScript compiler.

Overview

Try moving your cursor into the code block below:

ts
ts
// Removes 'readonly' attributes from a type's properties
type CreateMutable<Type> = {
-readonly [Property in keyof Type]: Type[Property]
}
 
type LockedAccount = {
readonly id: string
readonly name: string
}
 
type UnlockedAccount = CreateMutable<LockedAccount>
ts
// Removes 'readonly' attributes from a type's properties
type CreateMutable<Type> = {
-readonly [Property in keyof Type]: Type[Property]
}
 
type LockedAccount = {
readonly id: string
readonly name: string
}
 
type UnlockedAccount = CreateMutable<LockedAccount>

Pretty neat, right? To some extent, anything your editor can show you about code, Twoslash can show. For example, here is the real auto-complete for a VitePress config:

ts
ts
import { defineConfig } from 'vitepress'
 
export default defineConfig({
ti,
      
})
ts
import { defineConfig } from 'vitepress'
 
export default defineConfig({
ti,
      
})

The name Twoslash refers to specially formatted comments (e.g. // ^?) which can be used to set up your environment, like compiler flags or separate input files. It couldn't be easier to set up and start creating incredible code examples!

Install

Install @andatoshiki/vitepress-plugin-shiki-twoslash (requires vitepress@>=1.0.0-alpha.61).

bash
pnpm add @andatoshiki/vitepress-plugin-shiki-twoslash
pnpm add @andatoshiki/vitepress-plugin-shiki-twoslash
bash
npm i @andatoshiki/vitepress-plugin-shiki-twoslash
npm i @andatoshiki/vitepress-plugin-shiki-twoslash
bash
yarn add @andatoshiki/vitepress-plugin-shiki-twoslash
yarn add @andatoshiki/vitepress-plugin-shiki-twoslash

WARNING

Until shiki-twoslash uses the same version of shiki as VitePress, you must override the following packages' shiki versions for syntax highlighting to look the same.

json
{
    "pnpm": {
        "overrides": {
            "remark-shiki-twoslash>shiki": "^0.14.1",
            "shiki-twoslash>shiki": "^0.14.1"
        }
    }
}
{
    "pnpm": {
        "overrides": {
            "remark-shiki-twoslash>shiki": "^0.14.1",
            "shiki-twoslash>shiki": "^0.14.1"
        }
    }
}

Tracked in an upstream issue: https://github.com/shikijs/twoslash/issues/180

Configure

First, wrap your VitePress config file with the withTwoslash wrapper.

ts
ts
// .vitepress/config.[ext]
import { defineConfig } from 'vitepress'
import { withTwoslash } from '@andatoshiki/vitepress-plugin-shiki-twoslash'
 
export default withTwoslash(
defineConfig({
// Your VitePress config
})
)
ts
// .vitepress/config.[ext]
import { defineConfig } from 'vitepress'
import { withTwoslash } from '@andatoshiki/vitepress-plugin-shiki-twoslash'
 
export default withTwoslash(
defineConfig({
// Your VitePress config
})
)

Then, import @andatoshiki/vitepress-plugin-shiki-twoslash/styles.css into your theme.

ts
ts
// .vitepress/theme/index.ts
import defaultTheme from 'vitepress/theme'
import '@andatoshiki/vitepress-plugin-shiki-twoslash/styles.css'
 
export default defaultTheme
ts
// .vitepress/theme/index.ts
import defaultTheme from 'vitepress/theme'
import '@andatoshiki/vitepress-plugin-shiki-twoslash/styles.css'
 
export default defaultTheme

TIP

You can configure VitePress Twoslash using the twoslash property added to defineConfig.

Add Twoslash

Finally, add the twoslash attribute to markdown fenced code blocks.

md
```ts twoslash
// Removes 'readonly' attributes from a type's properties
type CreateMutable<Type> = {
    -readonly [Property in keyof Type]: Type[Property]
}

type LockedAccount = {
    readonly id: string
    readonly name: string
}

type UnlockedAccount = CreateMutable<LockedAccount>
//   ^?
```
```ts twoslash
// Removes 'readonly' attributes from a type's properties
type CreateMutable<Type> = {
    -readonly [Property in keyof Type]: Type[Property]
}

type LockedAccount = {
    readonly id: string
    readonly name: string
}

type UnlockedAccount = CreateMutable<LockedAccount>
//   ^?
```

And your code blocks will be twoslashified!

ts
ts
// Removes 'readonly' attributes from a type's properties
type CreateMutable<Type> = {
-readonly [Property in keyof Type]: Type[Property]
}
 
type LockedAccount = {
readonly id: string
readonly name: string
}
 
type UnlockedAccount = CreateMutable<LockedAccount>
type UnlockedAccount = { id: string; name: string; }
ts
// Removes 'readonly' attributes from a type's properties
type CreateMutable<Type> = {
-readonly [Property in keyof Type]: Type[Property]
}
 
type LockedAccount = {
readonly id: string
readonly name: string
}
 
type UnlockedAccount = CreateMutable<LockedAccount>
type UnlockedAccount = { id: string; name: string; }
]]>
<![CDATA[謝辞 ]]> https://note.toshiki.dev/development/aws/acknowledgement https://note.toshiki.dev/development/aws/acknowledgement Thu, 01 Jul 2021 00:00:00 GMT 謝辞

本原稿の執筆にあたり,以下の方々からの協力を得た.この場を借りて,感謝を表したい.

2021 年バージョンの contributors

  • 香取真知子氏 - ハンズオンプログラムの動作確認,文章校閲

2020 年バージョンの contributors

  • 勝俣敬寛氏 - Docker イメージの作成

  • 香取真知子氏 - ハンズオンプログラムの動作確認

  • @shuuji3 - MR !15

  • @takatama_jp - MR !14

本書の執筆には Asciidoctor を使用した.

また,本書はオープンソースの教科書として,すべての読者・ディベロッパーからのフィードバックを受け付けている. 誤植や記述の誤り,改善点など見つかったら,ぜひ IssuesPull request を投稿していただきたい.

]]>
謝辞

本原稿の執筆にあたり,以下の方々からの協力を得た.この場を借りて,感謝を表したい.

2021 年バージョンの contributors

  • 香取真知子氏 - ハンズオンプログラムの動作確認,文章校閲

2020 年バージョンの contributors

  • 勝俣敬寛氏 - Docker イメージの作成

  • 香取真知子氏 - ハンズオンプログラムの動作確認

  • @shuuji3 - MR !15

  • @takatama_jp - MR !14

本書の執筆には Asciidoctor を使用した.

また,本書はオープンソースの教科書として,すべての読者・ディベロッパーからのフィードバックを受け付けている. 誤植や記述の誤り,改善点など見つかったら,ぜひ IssuesPull request を投稿していただきたい.

]]>
<![CDATA[Appendix: 環境構築 ]]> https://note.toshiki.dev/development/aws/appendix https://note.toshiki.dev/development/aws/appendix Thu, 01 Jul 2021 00:00:00 GMT Appendix: 環境構築

本書を読み進めるにあたって,ハンズオンのプログラムを実行するための環境を自分のローカルマシンにセットアップしなければならない. ここでは, AWS やコマンドラインの初心者を想定して,本章で必要なソフトウェアやライブラリのインストールなどを簡単に解説する. 以下に簡単な目次を示そう. 既に環境構築が済んでいる場合は適宜読み飛ばしていただき,関係のある箇所のみ目を通せば良い.

使用する OS は Linux/Mac/Windows のどれを用いても構わない. Windows のユーザーは, Windows Subsytem for Linux (WSL) を使用することを想定している (WSL のインストール).

また,本書のハンズオンを実行するための Docker イメージ を提供している. これを用いると, AWS CLI/CDK や Python の設定などをスキップできるので, Docker の使用方法を知っている読者には便利だろう.

AWS アカウントの取得

本書で提供するハンズオンを実際に自分で試すには,読者自身で AWS のアカウントの作成をする必要がある. 詳しいアカウントの作成の手順は 公式のドキュメンテーション に書かれているので,そちらも参照していただきたい. 以下の手順に従ってアカウントの作成を行う.

まず,ウェブブラウザから AWS コンソール にアクセスし,右上の Create an AWS Account をクリックする (figure_title で実線で囲った部分).

サインアップ (1): AWS コンソールにアクセス

次に,遷移した先のページでメールアドレスとパスワードなどの登録を行う (figure_title).

サインアップ (2): メールアドレス・パスワードなどの登録.

続いて,住所や電話番号などを訊かれるので,すべて入力しよう (figure_title).

サインアップ (3): 住所・電話番号の入力

次に,クレジットカードの情報の登録を求められる (figure_title). 個人で AWS を利用する場合は,利用料金の請求はクレジットカードを経由して行われる. クレジットカードの登録なしには AWS を使い始めることはできないことに注意.

サインアップ (4): クレジットカードの登録

次の画面では,携帯電話の SMS またはボイスメッセージを利用した本人確認が求められる (figure_title). 希望の認証方法を選択し,自分の携帯電話番号を入力しよう.

サインアップ (5): 携帯電話による本人確認

無事に本人確認が完了すると,最後にサポートプランの選択を求められる (figure_title). 無料の Basic support を選択しておけば問題ない.

サインアップ (6): サポートプランの選択

以上のステップにより,アカウントの作成が完了する (figure_title). 早速ログインをして, AWS コンソールにアクセスできるか確認しておこう.

サインアップ (7): アカウントの作成が完了した

AWS のシークレットキーの作成

AWS シークレットキーとは, AWS CLI や AWS CDK から AWS の API を操作するときに,ユーザー認証を行うための鍵のことである. AWS CLI/CDK を使うには,最初にシークレットキーを発行する必要がある. AWS シークレットキーの詳細は 公式ドキュメンテーション "Understanding and getting your AWS credentials" を参照.

  1. AWS コンソールにログインする.

  2. 画面右上のアカウント名をクリックし,表示されるプルダウンメニューから "My Security Credentials" を選択 (figure_title)

  3. "Access keys for CLI, SDK, & API access" の下にある "Create accesss key" のボタンをクリックする (figure_title)

  4. 表示された Access key ID, Secret access key を記録しておく (画面を閉じると二度と表示されない).

  5. 鍵を忘れてしまった場合などは,同じ手順で再発行が可能である.

  6. 発行したシークレットキーは, ~/.aws/credentials のファイルに書き込むか,環境変数に設定するなどして使う (詳しくは AWS CLI のインストール).

AWS シークレットキーの発行1

AWS シークレットキーの発行2

AWS Educate Starter Account を用いている場合は,次の手順でシークレットキーを確認する.

  • AWS Educate のコンソール画面から, vocareum のコンソールに移動する (figure_title).

  • Account Details をクリックし,続いて AWS CLI: Show をクリックする.

  • aws_access_key_id, aws_secret_access_key, aws_session_token が表示される (figure_title). ここで表示された内容を ~/.aws/credentials にコピーする (AWS CLI のインストール 参照). aws_session_token の箇所も漏らさずコピーすること.

  • 続いて, ~/.aws/config というファイルを用意し,次の内容を書き込む. 現時点では AWS Starter Account は us-east-1 リージョンでしか利用できないためである.

toml
[default]
    region = us-east-1
    output = json
[default]
    region = us-east-1
    output = json
  • 上記の説明ではプロファイル名が default となっていたが,これは自分の好きな名前に変更してもよい. default 以外の名前を使用する場合は,コマンドを実行するときにプロファイル名を指定する必要がある (詳しくは AWS CLI のインストール).

vocareum コンソール

vocareum から AWS シークレットキーの発行

AWS CLI のインストール

読者のために,執筆時点におけるインストールの手順 (Linux 向け) を簡単に記述する. 将来のバージョンでは変更される可能性があるので,常に 公式のドキュメンテーション で最新の情報をチェックすることを忘れずに.

sh
$ curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
$ unzip awscliv2.zip
$ sudo ./aws/install
$ curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
$ unzip awscliv2.zip
$ sudo ./aws/install

インストールできたか確認するため,次のコマンドを打ってバージョン情報が出力されることを確認する.

sh
$ aws --version
$ aws --version

インストールができたら,次のコマンドにより初期設定を行う (参照).

sh
$ aws configure
$ aws configure

コマンドを実行すると, AWS Access Key ID, AWS Secret Access Key を入力するよう指示される. シークレットキーの発行については AWS のシークレットキーの作成 を参照. コマンドは加えて,Default region name を訊いてくる. ここには自分の好きな地域 (例えば ap-northeast-1 =東京リージョン) を指定すればよい. 最後の Default output formatjson としておくとよい.

このコマンドを完了すると, ~/.aws/credentials~/.aws/config という名前のファイルが生成されているはずである. 念のため, cat コマンドを使って中身を確認してみるとよい.

sh
$ cat ~/.aws/credentials
[default]
aws_access_key_id = XXXXXXXXXXXXXXXXXX
aws_secret_access_key = YYYYYYYYYYYYYYYYYYY

$ cat ~/.aws/config
[profile default]
region = ap-northeast-1
output = json
$ cat ~/.aws/credentials
[default]
aws_access_key_id = XXXXXXXXXXXXXXXXXX
aws_secret_access_key = YYYYYYYYYYYYYYYYYYY

$ cat ~/.aws/config
[profile default]
region = ap-northeast-1
output = json

~/.aws/credentials には認証鍵の情報が, ~/.aws/config には AWS CLI の設定が記録されている.

デフォルトでは, [default] という名前でプロファイルが保存される. いくつかのプロファイルを使い分けたければ, default の例に従って,たとえば [myprofile] などという名前でプロファイルを追加すればよい.

AWS CLI でコマンドを打つときに,プロファイルを使い分けるには,

sh
$ aws s3 ls --profile myprofile
$ aws s3 ls --profile myprofile

のように, --profile というオプションをつけてコマンドを実行する.

いちいち --profile オプションをつけるのが面倒だと感じる場合は, AWS_PROFILE という環境変数を設定するとよい.

sh
$ export AWS_PROFILE=myprofile
$ export AWS_PROFILE=myprofile

あるいは,認証情報などを環境変数に設定するテクニックもある.

sh
export AWS_ACCESS_KEY_ID=XXXXXX
export AWS_SECRET_ACCESS_KEY=YYYYYY
export AWS_DEFAULT_REGION=ap-northeast-1
export AWS_ACCESS_KEY_ID=XXXXXX
export AWS_SECRET_ACCESS_KEY=YYYYYY
export AWS_DEFAULT_REGION=ap-northeast-1

これらの環境変数は, ~/.aws/credentials よりも高い優先度をもつので,環境変数が設定されていればそちらの情報が使用される (参照).

AWS Educate Starter Accountus-east-1 のリージョンのみ利用可能である (執筆時点での情報). よって, AWS Educate Starter Account を使用している場合は, default region を us-east-1 に設定する必要がある.

AWS CDK のインストール

読者のために,執筆時点におけるインストールの手順 (Linux 向け) を簡単に記述する. 将来のバージョンでは変更される可能性があるので,常に 公式のドキュメンテーション で最新の情報をチェックすることを忘れずに.

Node.js がインストールされていれば,基本的に次のコマンドを実行すればよい.

sh
$ sudo npm install -g aws-cdk
$ sudo npm install -g aws-cdk

本書のハンズオンは AWS CDK version 1.100.0 で開発した. CDK は開発途上のライブラリなので,将来的に API が変更される可能性がある. API の変更によりエラーが生じた場合は, version 1.100.0 を使用することを推奨する.

sh
$ npm install -g aws-cdk@1.100
$ npm install -g aws-cdk@1.100

インストールできたか確認するため,次のコマンドを打って正しくバージョンが表示されることを確認する.

sh
$ cdk --version
$ cdk --version

インストールができたら,次のコマンドにより AWS 側の初期設定を行う. これは一度実行すれば OK.

sh
$ cdk bootstrap
$ cdk bootstrap

cdk bootstrap を実行するときは,AWS の認証情報とリージョンが正しく設定されていることを確認する. デフォルトでは ~/.aws/config にあるデフォルトのプロファイルが使用される. デフォルト以外のプロファイルを用いるときは AWS CLI のインストール で紹介したテクニックを使って切り替える.

AWS CDK の認証情報の設定は AWS CLI と基本的に同じである.詳しくは AWS CLI のインストール を参照.

WSL のインストール

本書のハンズオンではコマンドラインから AWS CLI のコマンドを実行したり, Python で書かれたプログラムを実行する. コマンドは基本的に UNIX のターミナルを想定して書かれている. Linux や Mac のユーザーは OS に標準搭載されているターミナルを用いれば良い. Windows を利用している読者は, Windows Subsystem for Linux (WSL) を利用することで,仮想の Linux 環境を構築することを推奨する. Cygwin などの Linux 環境をエミュレートするほかのツールでも構わないが,本書のプログラムは WSL でのみ動作確認を行っている.

WSL とは, Windows の OS 上で Linux の仮想環境を起動するための, Microsoft 社が公式で提供しているソフトウェアである. Ubuntu など希望の Linux distribution が選択でき,基本的にすべての Linux 向けに作られたプログラム・ソフトウェアを使用することができる.

執筆時点では WSL 2 が最新版として提供されているので,以下では WSL 2 のインストール手順を簡単に説明する. 細かな詳細などは, 公式ドキュメンテーション を参照のこと.

前提として,使用される OS は Windows 10 (Pro または Home エディション) でなければならない. さらに,使用している Windows 10 のバージョンが WSL に対応するバージョンであるかを確認する. X64 のシステムでは Version 1903, Build 18362 以上でなければならない. バージョンが対応していない場合は、 Windows のアップデートを行う.

まず最初に, Administrator 権限で PowerShell を起動する (figure_title). 左下の Windows メニューの検索バーに powershell と入力すると, PowerShell のプログラムが見つかるはずである, これを右クリックし、 Run as administrator を選択し起動する.

管理者権限での PowerShell の起動

PowerShell が起動したら、次のコマンドを実行する.

powershell
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

実行して、“The operation completed successfully.” と出力されるのを確認する. これで WSL が enable される.

次に,先ほどと同じ Administrator 権限で開いた PowerShell で次のコマンドを実行する。

powershell
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

実行して, “The operation completed successfully.” と出力されるのを確認する. これが確認出来たら、一度コンピュータを再起動する.

続いて, Linux kernel update package を次のリンクからダウンロードする. https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi

ダウンロードしたファイルをダブルクリックして実行する. ダイアログに従ってインストールを完了させる.

そうしたら,再び PowerShell を開き次のコマンドを実行する。

powershell
wsl --set-default-version 2
wsl --set-default-version 2

最後に、自分の好みの Linux distribution をインストールする. ここでは Ubuntu 20.04 をインストールしよう.

Microsoft store のアプリを起動し,検索バーに Ubuntu と入力する. Ubuntu 20.04 LTS という項目が見つかるはずなので,それを開き, “Get” ボタンをクリックする (figure_title). しばらく待つと, Ubuntu 20.04 のインストールが完了する.

Microsoft store から Ubuntu 20.04 をインストール

Ubuntu 20.04 を初回に起動すると,初期設定が自動で開始され,数分待つことになる. 初期設定が終わると,ユーザー名・パスワードを設定するようプロンプトが出るので,プロンプトに従い入力する.

これで WSL2 のインストールが完了した. 早速 WSL2 を起動してみよう. 左下の Windows メニューの検索バーに Ubuntu と入力すると, Ubuntu 20.04 のプログラムが見つかるはずである (figure_title). クリックして起動しよう.

Ubuntu 20.04 の起動

すると,ターミナルの黒い画面が立ち上がるだろう (figure_title). ls, top などのコマンドを打ってみて, WSL がきちんと動作していることを確認しよう.

WSL の起動画面

オプションとして, Windows Terminal というマイクロソフトから提供されているツールを使うと,より快適に WSL を使用することができる. 興味のある読者はこちらのインストールも推奨する.

Docker のインストール

Docker のインストールの方法は OS によって異なる.

Mac ユーザーは, Docker Desktop をインストールする. インストールの方法は, Docker のウェブサイト から, Mac 版の Docker Desktop をダウンロードし,ダウンロードされたファイルをダブルクリックし, Applications のフォルダにドラッグするだけで良い. 詳細は 公式ドキュメンテーション を参照のこと.

Windows のユーザーは,Docker Desktop をインストールする. その際, WSL 2 が事前にインストールされていなければならない. 詳細は 公式ドキュメンテーション を参照のこと. Docker Desktop をインストールすると, WSL からも docker コマンドが使用できるようになる.

Linux ユーザー (特に Ubuntu ユーザー) については,インストールの方法はいくつかのアプローチがある. 公式ドキュメンテーション にいくつかのインストールの方法が示されているので,詳しい情報はそちらを参照いただきたい.

最も簡単な方法は, Docker が公式で提供しているインストールスクリプトを用いる方法である. この場合,次のコマンドを実行することで Docker がインストールされる.

sh
$ curl -fsSL https://get.docker.com -o get-docker.sh
$ sudo sh get-docker.sh
$ curl -fsSL https://get.docker.com -o get-docker.sh
$ sudo sh get-docker.sh

デフォルトのインストールでは, root ユーザーのみが docker コマンドを使用できる設定になっている. 従って,コマンドには毎回 sudo を付け加える必要がある. これが面倒だと感じる場合は,次のステップにより,使用するユーザーを docker というグループに追加する (詳細は 公式ドキュメンテーション "Post-installation steps for Linux" を参照).

まず最初に, docker という名前にグループを追加する. インストールによっては,既に docker グループが作られている場合もある.

sh
$ sudo groupadd docker
$ sudo groupadd docker

次に,現在使用しているユーザーを docker グループに加える.

sh
$ sudo usermod -aG docker $USER
$ sudo usermod -aG docker $USER

ここまでできたら,一度ログアウトし,再度ログインする. これによって,グループの変更がターミナルのセッションに反映される.

設定が正しくできているかを確認するため,次のコマンドを実行してみる.

sh
$ docker run hello-world
$ docker run hello-world

sudo なしでコンテナが実行できたならば,設定は完了である.

Python venv クイックガイド

他人からもらったプログラムで, numpy や scipy のバージョンが違う!などの理由で,プログラムが動かない,という経験をしたことがある人は多いのではないだろうか. もし,自分の計算機の中に一つしか Python 環境がないとすると,プロジェクトを切り替えるごとに正しいバージョンをインストールし直さなければならず,これは大変な手間である.

コードのシェアをよりスムーズにするためには,ライブラリのバージョンはプロジェクトごとに管理されるべきである. それを可能にするのが Python 仮想環境とよばれるツールであり, venv, pyenv, conda などがよく使われる.

そのなかでも, venv は Python に標準搭載されているのでとても便利である. pyenvconda は,別途インストールの必要があるが,それぞれの長所もある.

venv を使って仮想環境を作成するには,

sh
$ python -m venv .env
$ python -m venv .env

と実行する. これにより .env/ というディレクトリが作られ,このディレクトリに依存するライブラリが保存されることになる.

この新たな仮想環境を起動するには

sh
$ source .env/bin/activate
$ source .env/bin/activate

と実行する.

シェルのプロンプトに (.env) という文字が追加されていることを確認しよう (figure_title). これが, "いまあなたは venv の中にいますよ" というしるしになる.

venv を起動したときのプロンプト

仮想環境を起動すると,それ以降実行する pip コマンドは, .env/ 以下にインストールされる.このようにして,プロジェクトごとに使うライブラリのバージョンを切り分けることができる.

Python では requirements.txt というファイルに依存ライブラリを記述するのが一般的な慣例である.他人からもらったプログラムに, requirements.txt が定義されていれば,

sh
$ pip install -r requirements.txt
$ pip install -r requirements.txt

と実行することで,必要なライブラリをインストールし,瞬時に Python 環境を再現することができる.

venv による仮想環境を保存するディレクトリの名前は任意に選べることができるが, .env という名前を用いるのが一般的である.

ハンズオン実行用の Docker image の使い方

ハンズオンを実行するために必要な, Node.js, Python, AWS CDK などがインストールされた Docker image を用意した. これを使用することで,自分のローカルマシンに諸々をインストールする必要なく,すぐにハンズオンのコードが実行できる.

ハンズオンのいくつかのコマンドは Docker の外 = ローカルマシンのリアル環境で実行されなければならない. それらについてはハンズオンの該当箇所に注意書きとして記してある.

Docker イメージは Docker Hub においてある. Docker イメージのビルドファイルは GitHub の docker/Dockerfile にある.

次のコマンドでコンテナを起動する.

sh
$ docker run -it tomomano/labc:latest
$ docker run -it tomomano/labc:latest

初回にコマンドを実行したときのみ,イメージが Docker Hub からダウンロード (pull) される. 二回目以降はローカルにダウンロードされたイメージが使用される.

コンテナが起動すると,次のようなインタラクティブシェルが表示されるはずである (起動時に -it のオプションをつけたのがポイントである).

root@aws-handson:~$</programlisting>

この状態で ls コマンドを打つと, handson/ というディレクトリがあるはずである. ここに cd する.

sh
$ cd handson
$ cd handson

すると,各ハンズオンごとのディレクトリが見つかるはずである.

あとは,ハンズオンごとにディレクトリを移動し,ハンズオンごとの virtualenv を作成し,スタックのデプロイを行えばよい ( (#sec_handson_ec2_run) など参照). ハンズオンごとに使用する依存ライブラリが異なるので,それぞれのハンズオンごとに virtualenv を作成するという設計になっている.

AWS の認証情報を設定することも忘れずに. AWS CLI のインストール で記述したように, AWS_ACCESS_KEY_ID などの環境変数を設定するのが簡単な方法である. あるいは,ローカルマシンの ~/.aws/credentials に認証情報が書き込まれているなら,このディレクトリをコンテナにマウントすることで,同じ認証ファイルをコンテナ内部から参照することが可能である. この選択肢を取る場合は,次のコマンドでコンテナを起動する.

sh
$ docker run -it -v ~/.aws:/root/.aws:ro tomomano/labc:latest
$ docker run -it -v ~/.aws:/root/.aws:ro tomomano/labc:latest

これにより,ローカルマシンの ~/.aws をコンテナの /root/.aws にマウントすることができる. 最後の :ro は read-only を意味する. 大切な認証ファイルが誤って書き換えられてしまわないように, read-only のフラグをつけることをおすすめする.

/root/ がコンテナ環境におけるホームディレクトリである. ここで紹介した認証ファイルをマウントするテクニックは, SSH 鍵をコンテナに渡すときなどにも使える.

]]>
Appendix: 環境構築

本書を読み進めるにあたって,ハンズオンのプログラムを実行するための環境を自分のローカルマシンにセットアップしなければならない. ここでは, AWS やコマンドラインの初心者を想定して,本章で必要なソフトウェアやライブラリのインストールなどを簡単に解説する. 以下に簡単な目次を示そう. 既に環境構築が済んでいる場合は適宜読み飛ばしていただき,関係のある箇所のみ目を通せば良い.

使用する OS は Linux/Mac/Windows のどれを用いても構わない. Windows のユーザーは, Windows Subsytem for Linux (WSL) を使用することを想定している (WSL のインストール).

また,本書のハンズオンを実行するための Docker イメージ を提供している. これを用いると, AWS CLI/CDK や Python の設定などをスキップできるので, Docker の使用方法を知っている読者には便利だろう.

AWS アカウントの取得

本書で提供するハンズオンを実際に自分で試すには,読者自身で AWS のアカウントの作成をする必要がある. 詳しいアカウントの作成の手順は 公式のドキュメンテーション に書かれているので,そちらも参照していただきたい. 以下の手順に従ってアカウントの作成を行う.

まず,ウェブブラウザから AWS コンソール にアクセスし,右上の Create an AWS Account をクリックする (figure_title で実線で囲った部分).

サインアップ (1): AWS コンソールにアクセス

次に,遷移した先のページでメールアドレスとパスワードなどの登録を行う (figure_title).

サインアップ (2): メールアドレス・パスワードなどの登録.

続いて,住所や電話番号などを訊かれるので,すべて入力しよう (figure_title).

サインアップ (3): 住所・電話番号の入力

次に,クレジットカードの情報の登録を求められる (figure_title). 個人で AWS を利用する場合は,利用料金の請求はクレジットカードを経由して行われる. クレジットカードの登録なしには AWS を使い始めることはできないことに注意.

サインアップ (4): クレジットカードの登録

次の画面では,携帯電話の SMS またはボイスメッセージを利用した本人確認が求められる (figure_title). 希望の認証方法を選択し,自分の携帯電話番号を入力しよう.

サインアップ (5): 携帯電話による本人確認

無事に本人確認が完了すると,最後にサポートプランの選択を求められる (figure_title). 無料の Basic support を選択しておけば問題ない.

サインアップ (6): サポートプランの選択

以上のステップにより,アカウントの作成が完了する (figure_title). 早速ログインをして, AWS コンソールにアクセスできるか確認しておこう.

サインアップ (7): アカウントの作成が完了した

AWS のシークレットキーの作成

AWS シークレットキーとは, AWS CLI や AWS CDK から AWS の API を操作するときに,ユーザー認証を行うための鍵のことである. AWS CLI/CDK を使うには,最初にシークレットキーを発行する必要がある. AWS シークレットキーの詳細は 公式ドキュメンテーション "Understanding and getting your AWS credentials" を参照.

  1. AWS コンソールにログインする.

  2. 画面右上のアカウント名をクリックし,表示されるプルダウンメニューから "My Security Credentials" を選択 (figure_title)

  3. "Access keys for CLI, SDK, & API access" の下にある "Create accesss key" のボタンをクリックする (figure_title)

  4. 表示された Access key ID, Secret access key を記録しておく (画面を閉じると二度と表示されない).

  5. 鍵を忘れてしまった場合などは,同じ手順で再発行が可能である.

  6. 発行したシークレットキーは, ~/.aws/credentials のファイルに書き込むか,環境変数に設定するなどして使う (詳しくは AWS CLI のインストール).

AWS シークレットキーの発行1

AWS シークレットキーの発行2

AWS Educate Starter Account を用いている場合は,次の手順でシークレットキーを確認する.

  • AWS Educate のコンソール画面から, vocareum のコンソールに移動する (figure_title).

  • Account Details をクリックし,続いて AWS CLI: Show をクリックする.

  • aws_access_key_id, aws_secret_access_key, aws_session_token が表示される (figure_title). ここで表示された内容を ~/.aws/credentials にコピーする (AWS CLI のインストール 参照). aws_session_token の箇所も漏らさずコピーすること.

  • 続いて, ~/.aws/config というファイルを用意し,次の内容を書き込む. 現時点では AWS Starter Account は us-east-1 リージョンでしか利用できないためである.

toml
[default]
    region = us-east-1
    output = json
[default]
    region = us-east-1
    output = json
  • 上記の説明ではプロファイル名が default となっていたが,これは自分の好きな名前に変更してもよい. default 以外の名前を使用する場合は,コマンドを実行するときにプロファイル名を指定する必要がある (詳しくは AWS CLI のインストール).

vocareum コンソール

vocareum から AWS シークレットキーの発行

AWS CLI のインストール

読者のために,執筆時点におけるインストールの手順 (Linux 向け) を簡単に記述する. 将来のバージョンでは変更される可能性があるので,常に 公式のドキュメンテーション で最新の情報をチェックすることを忘れずに.

sh
$ curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
$ unzip awscliv2.zip
$ sudo ./aws/install
$ curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
$ unzip awscliv2.zip
$ sudo ./aws/install

インストールできたか確認するため,次のコマンドを打ってバージョン情報が出力されることを確認する.

sh
$ aws --version
$ aws --version

インストールができたら,次のコマンドにより初期設定を行う (参照).

sh
$ aws configure
$ aws configure

コマンドを実行すると, AWS Access Key ID, AWS Secret Access Key を入力するよう指示される. シークレットキーの発行については AWS のシークレットキーの作成 を参照. コマンドは加えて,Default region name を訊いてくる. ここには自分の好きな地域 (例えば ap-northeast-1 =東京リージョン) を指定すればよい. 最後の Default output formatjson としておくとよい.

このコマンドを完了すると, ~/.aws/credentials~/.aws/config という名前のファイルが生成されているはずである. 念のため, cat コマンドを使って中身を確認してみるとよい.

sh
$ cat ~/.aws/credentials
[default]
aws_access_key_id = XXXXXXXXXXXXXXXXXX
aws_secret_access_key = YYYYYYYYYYYYYYYYYYY

$ cat ~/.aws/config
[profile default]
region = ap-northeast-1
output = json
$ cat ~/.aws/credentials
[default]
aws_access_key_id = XXXXXXXXXXXXXXXXXX
aws_secret_access_key = YYYYYYYYYYYYYYYYYYY

$ cat ~/.aws/config
[profile default]
region = ap-northeast-1
output = json

~/.aws/credentials には認証鍵の情報が, ~/.aws/config には AWS CLI の設定が記録されている.

デフォルトでは, [default] という名前でプロファイルが保存される. いくつかのプロファイルを使い分けたければ, default の例に従って,たとえば [myprofile] などという名前でプロファイルを追加すればよい.

AWS CLI でコマンドを打つときに,プロファイルを使い分けるには,

sh
$ aws s3 ls --profile myprofile
$ aws s3 ls --profile myprofile

のように, --profile というオプションをつけてコマンドを実行する.

いちいち --profile オプションをつけるのが面倒だと感じる場合は, AWS_PROFILE という環境変数を設定するとよい.

sh
$ export AWS_PROFILE=myprofile
$ export AWS_PROFILE=myprofile

あるいは,認証情報などを環境変数に設定するテクニックもある.

sh
export AWS_ACCESS_KEY_ID=XXXXXX
export AWS_SECRET_ACCESS_KEY=YYYYYY
export AWS_DEFAULT_REGION=ap-northeast-1
export AWS_ACCESS_KEY_ID=XXXXXX
export AWS_SECRET_ACCESS_KEY=YYYYYY
export AWS_DEFAULT_REGION=ap-northeast-1

これらの環境変数は, ~/.aws/credentials よりも高い優先度をもつので,環境変数が設定されていればそちらの情報が使用される (参照).

AWS Educate Starter Accountus-east-1 のリージョンのみ利用可能である (執筆時点での情報). よって, AWS Educate Starter Account を使用している場合は, default region を us-east-1 に設定する必要がある.

AWS CDK のインストール

読者のために,執筆時点におけるインストールの手順 (Linux 向け) を簡単に記述する. 将来のバージョンでは変更される可能性があるので,常に 公式のドキュメンテーション で最新の情報をチェックすることを忘れずに.

Node.js がインストールされていれば,基本的に次のコマンドを実行すればよい.

sh
$ sudo npm install -g aws-cdk
$ sudo npm install -g aws-cdk

本書のハンズオンは AWS CDK version 1.100.0 で開発した. CDK は開発途上のライブラリなので,将来的に API が変更される可能性がある. API の変更によりエラーが生じた場合は, version 1.100.0 を使用することを推奨する.

sh
$ npm install -g aws-cdk@1.100
$ npm install -g aws-cdk@1.100

インストールできたか確認するため,次のコマンドを打って正しくバージョンが表示されることを確認する.

sh
$ cdk --version
$ cdk --version

インストールができたら,次のコマンドにより AWS 側の初期設定を行う. これは一度実行すれば OK.

sh
$ cdk bootstrap
$ cdk bootstrap

cdk bootstrap を実行するときは,AWS の認証情報とリージョンが正しく設定されていることを確認する. デフォルトでは ~/.aws/config にあるデフォルトのプロファイルが使用される. デフォルト以外のプロファイルを用いるときは AWS CLI のインストール で紹介したテクニックを使って切り替える.

AWS CDK の認証情報の設定は AWS CLI と基本的に同じである.詳しくは AWS CLI のインストール を参照.

WSL のインストール

本書のハンズオンではコマンドラインから AWS CLI のコマンドを実行したり, Python で書かれたプログラムを実行する. コマンドは基本的に UNIX のターミナルを想定して書かれている. Linux や Mac のユーザーは OS に標準搭載されているターミナルを用いれば良い. Windows を利用している読者は, Windows Subsystem for Linux (WSL) を利用することで,仮想の Linux 環境を構築することを推奨する. Cygwin などの Linux 環境をエミュレートするほかのツールでも構わないが,本書のプログラムは WSL でのみ動作確認を行っている.

WSL とは, Windows の OS 上で Linux の仮想環境を起動するための, Microsoft 社が公式で提供しているソフトウェアである. Ubuntu など希望の Linux distribution が選択でき,基本的にすべての Linux 向けに作られたプログラム・ソフトウェアを使用することができる.

執筆時点では WSL 2 が最新版として提供されているので,以下では WSL 2 のインストール手順を簡単に説明する. 細かな詳細などは, 公式ドキュメンテーション を参照のこと.

前提として,使用される OS は Windows 10 (Pro または Home エディション) でなければならない. さらに,使用している Windows 10 のバージョンが WSL に対応するバージョンであるかを確認する. X64 のシステムでは Version 1903, Build 18362 以上でなければならない. バージョンが対応していない場合は、 Windows のアップデートを行う.

まず最初に, Administrator 権限で PowerShell を起動する (figure_title). 左下の Windows メニューの検索バーに powershell と入力すると, PowerShell のプログラムが見つかるはずである, これを右クリックし、 Run as administrator を選択し起動する.

管理者権限での PowerShell の起動

PowerShell が起動したら、次のコマンドを実行する.

powershell
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

実行して、“The operation completed successfully.” と出力されるのを確認する. これで WSL が enable される.

次に,先ほどと同じ Administrator 権限で開いた PowerShell で次のコマンドを実行する。

powershell
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

実行して, “The operation completed successfully.” と出力されるのを確認する. これが確認出来たら、一度コンピュータを再起動する.

続いて, Linux kernel update package を次のリンクからダウンロードする. https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi

ダウンロードしたファイルをダブルクリックして実行する. ダイアログに従ってインストールを完了させる.

そうしたら,再び PowerShell を開き次のコマンドを実行する。

powershell
wsl --set-default-version 2
wsl --set-default-version 2

最後に、自分の好みの Linux distribution をインストールする. ここでは Ubuntu 20.04 をインストールしよう.

Microsoft store のアプリを起動し,検索バーに Ubuntu と入力する. Ubuntu 20.04 LTS という項目が見つかるはずなので,それを開き, “Get” ボタンをクリックする (figure_title). しばらく待つと, Ubuntu 20.04 のインストールが完了する.

Microsoft store から Ubuntu 20.04 をインストール

Ubuntu 20.04 を初回に起動すると,初期設定が自動で開始され,数分待つことになる. 初期設定が終わると,ユーザー名・パスワードを設定するようプロンプトが出るので,プロンプトに従い入力する.

これで WSL2 のインストールが完了した. 早速 WSL2 を起動してみよう. 左下の Windows メニューの検索バーに Ubuntu と入力すると, Ubuntu 20.04 のプログラムが見つかるはずである (figure_title). クリックして起動しよう.

Ubuntu 20.04 の起動

すると,ターミナルの黒い画面が立ち上がるだろう (figure_title). ls, top などのコマンドを打ってみて, WSL がきちんと動作していることを確認しよう.

WSL の起動画面

オプションとして, Windows Terminal というマイクロソフトから提供されているツールを使うと,より快適に WSL を使用することができる. 興味のある読者はこちらのインストールも推奨する.

Docker のインストール

Docker のインストールの方法は OS によって異なる.

Mac ユーザーは, Docker Desktop をインストールする. インストールの方法は, Docker のウェブサイト から, Mac 版の Docker Desktop をダウンロードし,ダウンロードされたファイルをダブルクリックし, Applications のフォルダにドラッグするだけで良い. 詳細は 公式ドキュメンテーション を参照のこと.

Windows のユーザーは,Docker Desktop をインストールする. その際, WSL 2 が事前にインストールされていなければならない. 詳細は 公式ドキュメンテーション を参照のこと. Docker Desktop をインストールすると, WSL からも docker コマンドが使用できるようになる.

Linux ユーザー (特に Ubuntu ユーザー) については,インストールの方法はいくつかのアプローチがある. 公式ドキュメンテーション にいくつかのインストールの方法が示されているので,詳しい情報はそちらを参照いただきたい.

最も簡単な方法は, Docker が公式で提供しているインストールスクリプトを用いる方法である. この場合,次のコマンドを実行することで Docker がインストールされる.

sh
$ curl -fsSL https://get.docker.com -o get-docker.sh
$ sudo sh get-docker.sh
$ curl -fsSL https://get.docker.com -o get-docker.sh
$ sudo sh get-docker.sh

デフォルトのインストールでは, root ユーザーのみが docker コマンドを使用できる設定になっている. 従って,コマンドには毎回 sudo を付け加える必要がある. これが面倒だと感じる場合は,次のステップにより,使用するユーザーを docker というグループに追加する (詳細は 公式ドキュメンテーション "Post-installation steps for Linux" を参照).

まず最初に, docker という名前にグループを追加する. インストールによっては,既に docker グループが作られている場合もある.

sh
$ sudo groupadd docker
$ sudo groupadd docker

次に,現在使用しているユーザーを docker グループに加える.

sh
$ sudo usermod -aG docker $USER
$ sudo usermod -aG docker $USER

ここまでできたら,一度ログアウトし,再度ログインする. これによって,グループの変更がターミナルのセッションに反映される.

設定が正しくできているかを確認するため,次のコマンドを実行してみる.

sh
$ docker run hello-world
$ docker run hello-world

sudo なしでコンテナが実行できたならば,設定は完了である.

Python venv クイックガイド

他人からもらったプログラムで, numpy や scipy のバージョンが違う!などの理由で,プログラムが動かない,という経験をしたことがある人は多いのではないだろうか. もし,自分の計算機の中に一つしか Python 環境がないとすると,プロジェクトを切り替えるごとに正しいバージョンをインストールし直さなければならず,これは大変な手間である.

コードのシェアをよりスムーズにするためには,ライブラリのバージョンはプロジェクトごとに管理されるべきである. それを可能にするのが Python 仮想環境とよばれるツールであり, venv, pyenv, conda などがよく使われる.

そのなかでも, venv は Python に標準搭載されているのでとても便利である. pyenvconda は,別途インストールの必要があるが,それぞれの長所もある.

venv を使って仮想環境を作成するには,

sh
$ python -m venv .env
$ python -m venv .env

と実行する. これにより .env/ というディレクトリが作られ,このディレクトリに依存するライブラリが保存されることになる.

この新たな仮想環境を起動するには

sh
$ source .env/bin/activate
$ source .env/bin/activate

と実行する.

シェルのプロンプトに (.env) という文字が追加されていることを確認しよう (figure_title). これが, "いまあなたは venv の中にいますよ" というしるしになる.

venv を起動したときのプロンプト

仮想環境を起動すると,それ以降実行する pip コマンドは, .env/ 以下にインストールされる.このようにして,プロジェクトごとに使うライブラリのバージョンを切り分けることができる.

Python では requirements.txt というファイルに依存ライブラリを記述するのが一般的な慣例である.他人からもらったプログラムに, requirements.txt が定義されていれば,

sh
$ pip install -r requirements.txt
$ pip install -r requirements.txt

と実行することで,必要なライブラリをインストールし,瞬時に Python 環境を再現することができる.

venv による仮想環境を保存するディレクトリの名前は任意に選べることができるが, .env という名前を用いるのが一般的である.

ハンズオン実行用の Docker image の使い方

ハンズオンを実行するために必要な, Node.js, Python, AWS CDK などがインストールされた Docker image を用意した. これを使用することで,自分のローカルマシンに諸々をインストールする必要なく,すぐにハンズオンのコードが実行できる.

ハンズオンのいくつかのコマンドは Docker の外 = ローカルマシンのリアル環境で実行されなければならない. それらについてはハンズオンの該当箇所に注意書きとして記してある.

Docker イメージは Docker Hub においてある. Docker イメージのビルドファイルは GitHub の docker/Dockerfile にある.

次のコマンドでコンテナを起動する.

sh
$ docker run -it tomomano/labc:latest
$ docker run -it tomomano/labc:latest

初回にコマンドを実行したときのみ,イメージが Docker Hub からダウンロード (pull) される. 二回目以降はローカルにダウンロードされたイメージが使用される.

コンテナが起動すると,次のようなインタラクティブシェルが表示されるはずである (起動時に -it のオプションをつけたのがポイントである).

root@aws-handson:~$</programlisting>

この状態で ls コマンドを打つと, handson/ というディレクトリがあるはずである. ここに cd する.

sh
$ cd handson
$ cd handson

すると,各ハンズオンごとのディレクトリが見つかるはずである.

あとは,ハンズオンごとにディレクトリを移動し,ハンズオンごとの virtualenv を作成し,スタックのデプロイを行えばよい ( (#sec_handson_ec2_run) など参照). ハンズオンごとに使用する依存ライブラリが異なるので,それぞれのハンズオンごとに virtualenv を作成するという設計になっている.

AWS の認証情報を設定することも忘れずに. AWS CLI のインストール で記述したように, AWS_ACCESS_KEY_ID などの環境変数を設定するのが簡単な方法である. あるいは,ローカルマシンの ~/.aws/credentials に認証情報が書き込まれているなら,このディレクトリをコンテナにマウントすることで,同じ認証ファイルをコンテナ内部から参照することが可能である. この選択肢を取る場合は,次のコマンドでコンテナを起動する.

sh
$ docker run -it -v ~/.aws:/root/.aws:ro tomomano/labc:latest
$ docker run -it -v ~/.aws:/root/.aws:ro tomomano/labc:latest

これにより,ローカルマシンの ~/.aws をコンテナの /root/.aws にマウントすることができる. 最後の :ro は read-only を意味する. 大切な認証ファイルが誤って書き換えられてしまわないように, read-only のフラグをつけることをおすすめする.

/root/ がコンテナ環境におけるホームディレクトリである. ここで紹介した認証ファイルをマウントするテクニックは, SSH 鍵をコンテナに渡すときなどにも使える.

]]>
<![CDATA[課題 ]]> https://note.toshiki.dev/development/aws/assignments https://note.toshiki.dev/development/aws/assignments Thu, 01 Jul 2021 00:00:00 GMT 課題

以下の課題を提出.

]]>
課題

以下の課題を提出.

]]>
<![CDATA[著者紹介 ]]> https://note.toshiki.dev/development/aws/author https://note.toshiki.dev/development/aws/author Thu, 01 Jul 2021 00:00:00 GMT 著者紹介

真野 智之 (Tomoyuki Mano)

情報理工学博士 (東京大学大学院情報理工学系研究科システム情報学専攻). 2021 年より日本学術振興会特別研究員 (PD) (現職). 沖縄科学技術大学院大学 (OIST) にてポスドク研究員として働く. 現在の研究分野は神経科学・神経情報学. 趣味は料理・ランニング・鉄道・アニメ,村上春樹の熱烈な愛読家.

連絡先 tomoyukimano@gmail.com

GitHub https://github.com/tomomano

]]>
著者紹介

真野 智之 (Tomoyuki Mano)

情報理工学博士 (東京大学大学院情報理工学系研究科システム情報学専攻). 2021 年より日本学術振興会特別研究員 (PD) (現職). 沖縄科学技術大学院大学 (OIST) にてポスドク研究員として働く. 現在の研究分野は神経科学・神経情報学. 趣味は料理・ランニング・鉄道・アニメ,村上春樹の熱烈な愛読家.

連絡先 tomoyukimano@gmail.com

GitHub https://github.com/tomomano

]]>
<![CDATA[Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する ]]> https://note.toshiki.dev/development/aws/aws-batch https://note.toshiki.dev/development/aws/aws-batch Thu, 01 Jul 2021 00:00:00 GMT Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する

ハンズオン第三回では, ECS と Fargate を使って自動質問回答システムを構築した. シンプルながらも,複数の質問が送られた場合には並列にジョブが実行され,ユーザーに答えが返されるシステムを作ることができた. ここでは,すでに学習済みの言語モデルを用いてアプリケーションを構築した. しかし,一般的に言って,機械学習のワークフローでは自分で作ったモデルを訓練することが最初のステップにあるはずである. そこで,ハンズオン第四回では,クラウドを用いて機械学習の訓練を並列化・高速化することを考える.

本ハンズオンでは深層学習におけるハイパーパラメータ最適化を取り上げる. ハイパーパラメータとは,勾配降下法によって最適化されるニューラルネットのパラメータの外にあるパラメータのことであり,具体的にはモデルの層の幅・深さなどネットワークのアーキテクチャに関わるもの,学習率やモメンタムなどパラメータの更新則に関わるものなどが含まる. 深層学習においてハイパーパラメータの調整はとても重要なタスクである. しかしながら,ハイパーパラメータを調整するには,少しずつ条件を変えながら何度もニューラルネットを学習させる必要があり,多くの計算時間がかかる. 研究・開発においては,スループットよくたくさんのモデルの可能性を探索することが生産性を決める重要なファクターであり,ハイパーパラメータ探索を高速に解くという問題は極めて関心が高い. 本ハンズオンでは,クラウドの強力な計算リソースを利用して並列的にニューラルネットの訓練を実行することで,この問題を解く方法を学んでいこう.

Auto scaling groups (ASG)

ハンズオンに入っていく前に, Auto scaling groups (ASG) とよばれる EC2 の概念を知っておく必要がある.

ECS の概要を示した (#ecs_overview) を振り返って見てほしい. 前章 ( (#sec_fargate_qabot)) でも説明したが, ECS のクラスターで計算を担う実体としては EC2 と Fargate を指定することができる. Fargate については前章で記述した. Fargate を用いると,自在にスケールする計算環境をとても簡単な設定で構築することができた. しかし, GPU を利用することができないなど,いくつかの制約があった. EC2 を使用した計算環境を指定することで,プログラミングの複雑度は増すが, GPU やその他のより高度かつ複雑な設定を伴ったクラスターを構築することができる.

EC2 クラスターには ASG と呼ばれるサービスが配置される. ASG は複数の EC2 インスタンスをロジカルな単位でグループ化することでクラスターを構成する. ASG はクラスター内に新しいインスタンスを起動する,あるいは不要になったインスタンスを停止するなどのスケーリングを担う. ASG で重要な概念として, desired capacity, minimum capacity, maximum capacity というパラメータがある. minimum capacity, maximum capacity は,それぞれクラスター内に配置できるインスタンスの数の最小値・最大値を指定するパラメータである. 前者は,クラスターに負荷がかかっていない場合でもアイドリング状態にあるインスタンスを維持することで,急に負荷が増大した時などのバッファーとして作用することができる. 後者は,負荷が急に増えたときに,過剰な数のインスタンスが起動する事態を防ぎ,経済的なコストの上限を定める役割を果たす.

desired capacity が,その時々でシステムが要求するインスタンスの数を指定する. desired capacity は,例えば 24 時間のリズムに合わせてインスタンスの数を増減させる (昼は多く夜は少なくなど) などの決まったスケジュールに基づいた設定を適用することができる. あるいはクラスター全体にかかっている負荷に応じて, desired capacity を動的に制御することも可能である. どのような基準でクラスターのスケーリングを行うかを定めるルールのことを,スケーリングポリシーとよぶ. たとえば,クラスター全体の稼働率 (負荷) を常に 80% に維持する,などのスケーリングポリシーが想定できる. この場合,クラスター全体の負荷が 80%を下回ったときにはクラスターからインスタンスが削除され,80%を超える (あるいは超えると予測される) 場合はインスタンスを追加する,という操作が ASG によって自動的に行われる.

上記のようなパラメータを検討し,ユーザーは ASG を作成する. ASG を作成したのち, ECS との連携をプログラムしてあげることで, ECS を介して ASG による EC2 クラスターにタスクを投入することが可能になる.

AWS Batch

AWS Batch のアイコン

先に説明したように, ECS と ASG を組み合わせることで,所望の計算クラスターを構築することが可能である. しかしながら, ECS と ASG にはかなり込み入った設定が必要であり,初心者にとっても経験者にとってもなかなか面倒なプログラミングが要求される. そこで, ECS と ASG によるクラスターの設計を自動化してくれるサービスが提供されている. それが AWS Batch である.

AWS Batch はその名のとおりバッチ (Batch) 化されたジョブ (入力データだけが異なる独立した演算が繰り返し実行されること) を想定している. 多くの科学計算や機械学習がバッチ計算に当てはまる. たとえば,初期値のパラメータを変えて複数のシミュレーションを走らせる,といったケースだ. AWS Batch を用いることの利点は,クラスターのスケーリングやジョブの割り振りはすべて自動で実行され, ユーザーはクラウドの舞台裏の詳細を気にすることなく,大量のジョブを投入できるシステムが手に入る点である. が,知識として背後では ECS/ASG/EC2 の三つ巴が協調して動作しているという点は知っておいてほしい.

AWS Batch では,ジョブの投入・管理をスムーズに行うため,次のような概念が定義されている (figure_title). まず, ジョブ (Job) というのが,AWS Batch によって実行される一つの計算の単位である. Job definitions とはジョブの内容を定義するものであり,これには実行されるべき Docker のイメージのアドレスや,割り当てる CPU・RAM の容量,環境変数などの設定が含まれる. Job definition に基づいて個々のジョブが実行される. ジョブが実行されると,ジョブは Job queues に入る. Job queues とは,実行待ち状態にあるジョブの列のことであり,時間的に最も先頭に投入されたジョブが最初に実行される. また,複数の queue を配置し, queue ごとに priority (優先度) を設定することが可能であり, priority の高い queue に溜まったジョブが優先的に実行される (筆者はこれをディズニーランドの"ファストパス"を連想して捉えている). Compute environment とは,先述したクラスターとほぼ同義の概念であり,計算が実行される場所 (EC2 や Fargate からなるクラスター) を指す. Compute environment には,使用する EC2 のインスタンスタイプや同時に起動するインスタンス数の上限などの簡易なスケーリングポリシーが指定されている. Job queues は Compute environment の空き状況を監視しており, それに応じてジョブを Compute environment に投下する.

以上が AWS Batch を使用するうえで理解しておかなければならない概念であるが,くどくど言葉で説明してもなかなかピンとこないだろう. ここからは,実際に自分で手を動かしながら学んでいこう.

AWS Batch の主要な概念

EC2 or Fargate?

ECS でクラスターを構成する際,計算を実行する場として EC2 と Fargate の二つの選択肢があることを説明した. それぞれ長所と短所を抱えているのだが,どのような場合にどちらを使うべきだろうか? それを検討するため,まずは table_title を見てみよう. これは EC2 と Fargate の特徴をまとめたものである. 説明の都合上,大幅な粗視化が行われている点は留意していただきたい.

EC2 vs Fargate
EC2Fargate

Compute capacity

Medium to large

Small to medium

GPU

Yes

No

Launch speed

Slow

Fast

Task placement flexibility

Low

High

Programming complexity

High

Low

これまでに見てきたように, EC2 は最大の CPU 数・メモリーサイズが大きかったり, GPU を利用できたりするなど,単一のインスタンスでの計算能力は高い. 対して, Fargate は単一インスタンスの最大 CPU 数は 4 コアが上限である. その一方で,インスタンスの起動に要する時間は Fargate のほうが圧倒的に早く,より俊敏にクラスターのスケーリングを行うことができる. また,タスクをクラスターに投入する際のフレキシビリティも Fargate のほうが高い. フレキシビリティというのは,例えば一つのインスタンスで 2 つ以上のコンテナを走らせる,などの状況である. 単位 CPU あたりで処理されるタスクの数を最大化する際には,このような設計がしばしば採用される. プログラミングの複雑さという観点からは, Fargate のほうが一般的にシンプルな実装になる.

このように, EC2 と Fargate は互いに相補的な特性を有しており,アプリケーションによって最適な計算環境は検討される必要がある. また,EC2 と Fargate を両方用いたハイブリッドクラスターというのも定義可能であり,そのような選択肢もしばしば用いられる.

準備

ハンズオンのソースコードは GitHub の handson/aws-batch にある.

本ハンズオンの実行には,第一回ハンズオンで説明した準備 ( (#handson_01_prep)) が整っていることを前提とする. また, Docker が自身のローカルマシンにインストール済みであることも必要である.

このハンズオンは, g4dn.xlarge タイプの EC2 インスタンスを使うので,アメリカ東部 (us-east-1) リージョンでは 0.526 $/hour のコストが発生する. 東京 (ap-northeast-1) を選択した場合は 0.71 $/hour のコストが発生する.

(#sec:jupyter_and_deep_learning_setup) でも注意したが,このハンズオンを始める前に G タイプインスタンスの起動上限を AWS コンソールの EC2 管理画面から確認しよう. もし上限が 0 になっていた場合は,上限緩和の申請を行う必要がある. アプリケーションの説明 にも関連した情報を記載しているので,併せて参照されたい.

MNIST 手書き文字認識 (再訪)

今回のハンズオンでは,機械学習のハイパーパラメータ調整を取り上げると冒頭で述べた. その最もシンプルな例題として, (#sec_mnist_using_jupyter) で扱った MNIST 手書き文字認識の問題を再度取り上げよう. (#sec_mnist_using_jupyter) では,適当にチョイスしたハイパーパラメータを用いてモデルの訓練を行った. ここで使用したプログラムのハイパーパラメータとしては,確率的勾配降下法 (SGD) における学習率やモメンタムが含まれる. コードでいうと,次の行が該当する.

python
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)

ここで使用された 学習率 (lr=0.01) やモメンタム (momentum=0.5) は恣意的に選択された値であり,これがベストな数値であるのかはわからない. たまたまこのチョイスが最適であるかもしれないし,もっと高い精度を出すハイパーパラメータの組が存在するかもしれない. この問題に答えるため,ハイパーパラメータサーチを行おう. 今回は,最もシンプルなアプローチとして,グリッドサーチによるハイパーパラメータサーチを行おう.

機械学習のハイパーパラメータの最適化には大きく3つのアプローチが挙げられる. グリッドサーチ,ランダムサーチ,そしてベイズ最適化による方法である.

グリッドサーチとは,ハイパーパラメータの組をある範囲の中で可能な組み合わせをすべて計算し,最適なパラメータの組を見出す方法である. 最もシンプルかつ確実な方法であるが,すべての組み合わせの可能性を愚直に計算するので計算コストが大きい.

ランダムサーチ法とは,ハイパーパラメータの組をある範囲の中でランダムに抽出し,大量に試行されたランダムな組の中から最適なパラメータの組を見出す方法である. すべての可能性を網羅的に探索できるわけではないが,調整すべきパラメータの数が多数ある場合に,グリッドサーチよりも効率的に広い探索空間をカバーすることができる.

ベイズ最適化を用いた方法では,過去の探索結果から次にどの組み合わせを探索すべきかという指標を計算し,次に探索するパラメータを決定する. これにより,理論的にはグリッドサーチやランダムサーチ法よりも少ない試行回数で最適なパラメータにたどり着くことができる.

並列化の観点でいうと,グリッドサーチとランダムサーチは各ハイパーパラメータの組の計算は独立に実行することができるため並列化が容易である. このように独立したジョブとして分割・並列化可能な問題を Embarrassingly parallel な問題とよぶ (直訳すると"恥ずかしいほど並列化可能な問題",ということになる). Embarrassingly parallel な問題はクラウドの強力な計算リソースを用いることで,非常なシンプルな実装で解くことができる. この章ではこのようなタイプの並列計算を取り上げる.

一方,ベイズ最適化による方法は,過去の結果をもとに次の探索が決定されるので,並列化はそれほど単純ではない. 最近では optuna などのハイパーパラメータ探索のためのライブラリが発達しており,ベイズ最適化の数理的な処理を自動で実行してくれるので便利である. これらのライブラリを使うと,もし一台のコンピュータ (ノード) の中に複数の GPU が存在する場合は,並列に計算を実行することができる. しかしながら,一台のノードにとどまらず,複数のノードをまたいだ並列化は,高度なプログラミングテクニックが必要とされるだけでなく,ノード間の接続様式などクラウドのアーキテクチャにも深く依存するものである. 本書ではここまで高度なクラウドの使用方法には立ち入らない.

まずは,本ハンズオンで使用する Docker イメージをローカルで実行してみよう.

Docker イメージのソースコードは handson/aws-batch/docker にある. 基本的に (#sec_mnist_using_jupyter) のハンズオンを元にし,本ハンズオン専用の軽微な変更が施してある. 興味のある読者はソースコードも含めて読んでいただきたい.

練習として,この Docker イメージを手元でビルドするところからはじめてみよう. Dockerfile が保存されているディレクトリに移動し, mymnist という名前 (Tag) をつけてビルドを実行する.

sh
$ cd handson/aws-batch/docker
$ docker build -t mymnist .
$ cd handson/aws-batch/docker
$ docker build -t mymnist .

docker build でエラーが出たときは次の可能性を疑ってほしい. ビルドの中で, MNIST の画像データセットを http://yann.lecun.com/exdb/mnist/ からダウンロードするのだが,ダウンロード先のサーバーがしばしばダウンしている. 世界中の機械学習ユーザーがアクセスするので,これはしばしば発生するようである. サーバーがダウンしているとビルドも失敗してしまう. エラーメッセージにそれらしい文言が含まれていたら,この可能性を疑おう.

手元でビルドするかわりに, Docker Hub から pull することも可能である. その場合は次のコマンドを実行する.

sh
$ docker pull tomomano/mymnist:latest
$ docker pull tomomano/mymnist:latest

イメージの準備ができたら,次のコマンドでコンテナを起動し, MNIST の学習を実行する..

sh
$ docker run mymnist --lr 0.1 --momentum 0.5 --epochs 10
$ docker run mymnist --lr 0.1 --momentum 0.5 --epochs 10

このコマンドを実行すると,指定したハイパーパラメータ (--lr で与えられる学習率と --momentum で与えられるモメンタム) を使ってニューラルネットの最適化が始まる. 学習を行う最大のエポック数は --epochs パラメータで指定する. (#sec_jupyter_and_deep_learning) のハンズオンで見たような, Loss の低下がコマンドライン上に出力されるだろう (figure_title).

Docker を実行した際の出力

上に示したコマンドを使うと,計算は CPU を使って実行される. もし,ローカルの計算機に GPU が備わっており, nvidia-docker の設定が済んでいるならば, 次のコマンドにより GPU を使って計算を実行できる.

$ docker run --gpus all mymnist --lr 0.1 --momentum 0.5 --epochs 10

このコマンドでは,--gpus all というパラメータが加わった.

CPU/GPU どちらで実行した場合でも,エポックを重ねるにつれて訓練データ (Train データ) の Loss は単調に減少していくのが見て取れるだろう. 一方,検証データ (Validation データ) の Loss および Accuracy は,ある程度まで減少した後,それ以上性能が向上しないことに気がつくだろう. これを実際にプロットしてみると figure_title のようになるはずである.

(左) Train/Validation データそれぞれの Loss のエポックごとの変化. (右) Validation データの Accuracy のエポックごとの変化

これはオーバーフィッティングとよばれる現象で,ニューラルネットが訓練データに過度に最適化され,訓練データの外のデータに対しての精度 (汎化性能) が向上していないことを示している. このような場合の対処法として, Early stopping とよばれるテクニックが知られている. Early stopping とは,検証データの Loss を追跡し,それが減少から増加に転じるエポックで学習をうち止め,そのエポックでのウェイトパラメータを採用する,というものである. 本ハンズオンでも, Early stopping によって訓練の終了を判断し,モデルの性能評価を行っていく.

MNIST 手書き文字データセットでは,訓練データとして 60,000 枚,テストデータとして 10,000 枚の画像が与えられている. 本ハンズオンで使用するコードでは,訓練データのうち 80% の 48,000 枚を訓練データとして使用し,残り 20% の 12,000 枚を検証データとして用いている. 詳しくはソースコードを参照のこと.

アプリケーションの説明

このハンズオンで作成するアプリケーションの概要を figure_title に示す.

アプリケーションのアーキテクチャ

簡単にまとめると,次のような設計である.

  • クライアントは,あるハイパーパラメータの組を指定して Batch にジョブを提出する

  • Batch はジョブを受け取ると, EC2 からなるクラスターで計算を実行する

  • クラスター内では g4dn.xlarge インスタンスが起動する

  • Docker イメージは, AWS 内に用意された ECR (Elastic Container Registry) から取得される

  • 複数のジョブが投下された場合は,その数だけのインスタンスが起動し並列に実行される

  • 各ジョブによる計算の結果は S3 に保存される

  • 最後にクライアントは S3 から結果をダウンロードし,最適なハイパーパラメータの組を決定する

それでは,プログラムのソースコードを見てみよう (handson/aws-batch/app.py).

python
class SimpleBatch(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        bucket = s3.Bucket(
            self, "bucket",
            removal_policy=core.RemovalPolicy.DESTROY,
            auto_delete_objects=True,
        )

        vpc = ec2.Vpc(
            self, "vpc",
            # other parameters...
        )

        #
        managed_env = batch.ComputeEnvironment(
            self, "managed-env",
            compute_resources=batch.ComputeResources(
                vpc=vpc,
                allocation_strategy=batch.AllocationStrategy.BEST_FIT,
                desiredv_cpus=0,
                maxv_cpus=64,
                minv_cpus=0,
                instance_types=[
                    ec2.InstanceType("g4dn.xlarge")
                ],
            ),
            managed=True,
            compute_environment_name=self.stack_name + "compute-env"
        )

        #
        job_queue = batch.JobQueue(
            self, "job-queue",
            compute_environments=[
                batch.JobQueueComputeEnvironment(
                    compute_environment=managed_env,
                    order=100
                )
            ],
            job_queue_name=self.stack_name + "job-queue"
        )

        #
        job_role = iam.Role(
            self, "job-role",
            assumed_by=iam.CompositePrincipal(
                iam.ServicePrincipal("ecs-tasks.amazonaws.com")
            )
        )
        # allow read and write access to S3 bucket
        bucket.grant_read_write(job_role)

        #
        repo = ecr.Repository(
            self, "repository",
            removal_policy=core.RemovalPolicy.DESTROY,
        )

        #
        job_def = batch.JobDefinition(
            self, "job-definition",
            container=batch.JobDefinitionContainer(
                image=ecs.ContainerImage.from_ecr_repository(repo),
                command=["python3", "main.py"],
                vcpus=4,
                gpu_count=1,
                memory_limit_mib=12000,
                job_role=job_role,
                environment={
                    "BUCKET_NAME": bucket.bucket_name
                }
            ),
            job_definition_name=self.stack_name + "job-definition",
            timeout=core.Duration.hours(2),
        )
class SimpleBatch(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        bucket = s3.Bucket(
            self, "bucket",
            removal_policy=core.RemovalPolicy.DESTROY,
            auto_delete_objects=True,
        )

        vpc = ec2.Vpc(
            self, "vpc",
            # other parameters...
        )

        #
        managed_env = batch.ComputeEnvironment(
            self, "managed-env",
            compute_resources=batch.ComputeResources(
                vpc=vpc,
                allocation_strategy=batch.AllocationStrategy.BEST_FIT,
                desiredv_cpus=0,
                maxv_cpus=64,
                minv_cpus=0,
                instance_types=[
                    ec2.InstanceType("g4dn.xlarge")
                ],
            ),
            managed=True,
            compute_environment_name=self.stack_name + "compute-env"
        )

        #
        job_queue = batch.JobQueue(
            self, "job-queue",
            compute_environments=[
                batch.JobQueueComputeEnvironment(
                    compute_environment=managed_env,
                    order=100
                )
            ],
            job_queue_name=self.stack_name + "job-queue"
        )

        #
        job_role = iam.Role(
            self, "job-role",
            assumed_by=iam.CompositePrincipal(
                iam.ServicePrincipal("ecs-tasks.amazonaws.com")
            )
        )
        # allow read and write access to S3 bucket
        bucket.grant_read_write(job_role)

        #
        repo = ecr.Repository(
            self, "repository",
            removal_policy=core.RemovalPolicy.DESTROY,
        )

        #
        job_def = batch.JobDefinition(
            self, "job-definition",
            container=batch.JobDefinitionContainer(
                image=ecs.ContainerImage.from_ecr_repository(repo),
                command=["python3", "main.py"],
                vcpus=4,
                gpu_count=1,
                memory_limit_mib=12000,
                job_role=job_role,
                environment={
                    "BUCKET_NAME": bucket.bucket_name
                }
            ),
            job_definition_name=self.stack_name + "job-definition",
            timeout=core.Duration.hours(2),
        )
  • で,計算結果を保存するための S3 バケットを用意している

  • で, Compute environment を定義している. ここでは g4dn.xlarge のインスタンスタイプを使用するとし,最大の vCPU 使用数は 64 と指定している. また,最小の vCPU は 0 である. 今回は,負荷がかかっていないときにアイドリング状態にあるインスタンスを用意する利点は全くないので,ここは 0 にするのが望ましい.

  • で, <2> で作成した Compute environment と紐付いた Job queue を定義している.

  • で,ジョブが計算結果を S3 に書き込むことができるよう, IAM ロールを定義している. (IAM とはリソースがもつ権限を管理する仕組みである.詳しくは (#sec:bashoutter_iam) を参照)

  • では, Docker image を配置するための ECR を定義している.

  • で Job definition を作成している. ここでは,4 vCPU, 12000 MB (=12GB) の RAM を使用するように指定している. また,今後必要となる環境変数 (BUCKET_NAME) を設定している. さらに, <4> で作った IAM を付与している.

g4dn.xlarge は 1 台あたり 4 vCPU が割り当てられている. このプログラムでは Compute environment の maximum vCPUs を 64 と指定しているので,最大で 16 台のインスタンスが同時に起動することになる. ここで maxium vCPUs を 64 に限定しているのは,なんらかのミスで意図せぬジョブを大量にクラスターに投入してしまった事態で,高額の AWS 利用料金が発生するのを防ぐためである. もし,自分のアプリケーションで必要と判断したならば自己責任において 64 よりも大きな数を設定して構わない.

ここで注意が一点ある. AWS では各アカウントごとに EC2 で起動できるインスタンスの上限が設定されている. この上限は AWS コンソールにログインし, EC2 コンソールの左側メニューバーの Limits をクリックすることで確認できる (figure_title). g4dn.xlarge (EC2 の区分でいうと G ファミリーに属する) の制限を確認するには, Running On-Demand All G instances という名前の項目を見る. ここにある数字が, AWS によって課されたアカウントの上限であり,この上限を超えたインスタンスを起動することはできない. もし,自分の用途に対して上限が低すぎる場合は,上限の緩和申請を行うことができる. 詳しくは 公式ドキュメンテーション "Amazon EC2 service quotas" を参照のこと.

EC2コンソールから各種の上限を確認する

スタックのデプロイ

スタックの中身が理解できたところで,早速スタックをデプロイしてみよう.

デプロイの手順は,これまでのハンズオンとほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). シークレットキーの設定も忘れずに ( (#aws_cli_install)).

sh
# プロジェクトのディレクトリに移動
$ cd handson/aws-batch

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd handson/aws-batch

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイのコマンドが無事に実行されたことが確認できたら,AWS コンソールにログインして,デプロイされたスタックを確認してみよう. コンソールの検索バーで batch と入力し, AWS Batch の管理画面を開く (figure_title).

AWS Batch のコンソール画面 (ダッシュボード)

まず目を向けてほしいのが,画面の一番下にある Compute environment overview の中の SimpleBatchcompute-env という名前の項目だ. Compute environment とは,先ほど述べたとおり,計算が実行される環境 (クラスターと読み替えてもよい) である. プログラムで指定したとおり, g4dn.xlarge が実際に使用されるインスタンスタイプとして表示されている. また, Minimum vCPUs が 0,Maximum vCPUs が 64 と設定されていることも見て取れる. 加えて,この時点では一つもジョブが走っていないので, Desired vCPUs は 0 になっている. より詳細な Compute environment の情報を閲覧したい場合は,名前をクリックすることで詳細画面が開く.

次に,Job queue overview にある SimpleBatch-queue という項目に注目してほしい. ここでは実行待ちのジョブ・実行中のジョブ・実行が完了したジョブを一覧で確認することができる. PENDING, RUNNING, SUCCEEDED, FAILED などのカラムがあることが確認できる.ジョブが進行するにつれて,ジョブの状態がこのカラムにしたがって遷移していく. 後でジョブを実際にサブミットしたときに戻ってこよう.

最後に,今回作成した Job definition を確認しよう. 左側のメニューから Job definitions を選択し,次の画面で SimpleBatchjob-definition という項目を見つけて開く. ここから Job definition の詳細を閲覧することができる (figure_title). 中でも重要な情報としては, vCPUs, Memory, GPU がそれぞれ Docker に割り当てられる vCPU・メモリー・ GPU の量を規定している. また, Image と書いてあるところに,ジョブで使用される Docker イメージが指定されている. ここでは, ECR のレポジトリを参照している. 現時点ではこの ECR は空である. 次のステップとして,この ECR にイメージを配置する作業を行おう.

AWS Batch から Job definition を確認

Docker image を ECR に配置する

さて, Batch がジョブを実行するには,どこか指定された場所から Docker イメージをダウンロード (pull) してくる必要がある. 前回のハンズオン ( (#sec_fargate_qabot)) では,公開設定にしてある Docker Hub からイメージを pull してきた. 今回のハンズオンでは, AWS から提供されているレジストリである ECR (Elastic Container Registry) に image を配置するという設計を採用する. ECR を利用する利点は,自分だけがアクセスすることのできるプライベートなイメージの置き場所を用意できる点である. Batch は ECR からイメージを pull してくることで,タスクを実行する (figure_title).

スタックのソースコードでいうと,次の箇所が ECR を定義している.

python
#
repo = ecr.Repository(
    self, "repository",
    removal_policy=core.RemovalPolicy.DESTROY,
)

job_def = batch.JobDefinition(
    self, "job-definition",
    container=batch.JobDefinitionContainer(
        image=ecs.ContainerImage.from_ecr_repository(repo), #
        ...
    ),
    ...
)
#
repo = ecr.Repository(
    self, "repository",
    removal_policy=core.RemovalPolicy.DESTROY,
)

job_def = batch.JobDefinition(
    self, "job-definition",
    container=batch.JobDefinitionContainer(
        image=ecs.ContainerImage.from_ecr_repository(repo), #
        ...
    ),
    ...
)
  • で,新規の ECR を作成している.

  • で Job definition を定義する中で,イメージを <1> で作った ECR から取得するように指定している. これと同時に, Job definition には ECR へのアクセス権限が IAM を通じて自動的に付与される.

さて,スタックをデプロイした時点では, ECR は空っぽである. ここに自分のアプリケーションで使う Docker イメージを push してあげる必要がある.

そのために,まずは AWS コンソールから ECR の画面を開こう (検索バーに Elastic Container Registry と入力すると出てくる). Private というタブを選択すると, simplebatch-repositoryXXXXXX という名前のレポジトリが見つかるだろう (figure_title).

ECR のコンソール画面

次に,このレポジトリの名前をクリックするとレポジトリの詳細画面に遷移する. そうしたら,画面右上にある View push commands というボタンをクリックする. すると figure_title のようなポップアップ画面が立ち上がる.

ECR への push コマンド

このポップアップ画面で表示されている四つのコマンドを順番に実行していくことで,手元の Docker イメージを ECR に push することができる. push を実行する前に, AWS の認証情報が設定されていることを確認しよう. そのうえで,ハンズオンのソースコードの中にある docker/ という名前のディレクトリに移動する. そうしたら,ポップアップ画面で表示されたコマンドを上から順に実行していく.

ポップアップで表示されるコマンドの 2 つめを見てみると docker build -t XXXXX . となっている. 最後の . が重要で,これは 現在のディレクトリにある Dockerfile を使ってイメージをビルドせよ という意味である. このような理由で, Dockerfile が置いてあるディレクトリに移動する必要がある.

四つ目のコマンドは,数 GB あるイメージを ECR にアップロードするので少し時間がかかるかもしれないが,これが完了するとめでたくイメージが ECR に配置されたことになる. もう一度 ECR のコンソールを見てみると,確かにイメージが配置されていることが確認できる (figure_title). これで,AWS Batch を使ってジョブを実行させるための最後の準備が完了した.

ECR へ image の配置が完了した

単一のジョブを実行する

さて,ここからは実際に AWS Batch にジョブを投入する方法を見ていこう.

ハンズオンのディレクトリの notebook/ というディレクトリの中に, run_single.ipynb というファイルが見つかるはずである (.ipynb は Jupyter notebook のファイル形式). これを Jupyter notebook から開こう.

今回のハンズオンでは, venv による仮想環境の中に Jupyter notebook もインストール済みである. なので,ローカルマシンから以下のコマンドで Jupyter notebook を立ち上げる.

sh
# .env の仮想環境にいることを確認
(.env) $ cd notebook
(.env) $ jupyter notebook
# .env の仮想環境にいることを確認
(.env) $ cd notebook
(.env) $ jupyter notebook

Jupyter notebook が起動したら, run_single.ipynb を開く.

最初の [1], [2], [3] 番のセルは,ジョブをサブミットするための関数 (submit_job()) を定義している.

python
# [1]
import boto3
import argparse

# [2]
# AWS 認証ヘルパー ...省略...

# [3]
def submit_job(lr:float, momentum:float, epochs:int, profile_name="default"):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    client = session.client("batch")

    title = "lr" + str(lr).replace(".", "") + "_m" + str(momentum).replace(".", "")
    resp = client.submit_job(
        jobName=title,
        jobQueue="SimpleBatchjob-queue",
        jobDefinition="SimpleBatchjob-definition",
        containerOverrides={
            "command": ["--lr", str(lr),
                        "--momentum", str(momentum),
                        "--epochs", str(epochs),
                        "--uploadS3", "true"]
        }
    )
    print("Job submitted!")
    print("job name", resp["jobName"], "job ID", resp["jobId"])
# [1]
import boto3
import argparse

# [2]
# AWS 認証ヘルパー ...省略...

# [3]
def submit_job(lr:float, momentum:float, epochs:int, profile_name="default"):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    client = session.client("batch")

    title = "lr" + str(lr).replace(".", "") + "_m" + str(momentum).replace(".", "")
    resp = client.submit_job(
        jobName=title,
        jobQueue="SimpleBatchjob-queue",
        jobDefinition="SimpleBatchjob-definition",
        containerOverrides={
            "command": ["--lr", str(lr),
                        "--momentum", str(momentum),
                        "--epochs", str(epochs),
                        "--uploadS3", "true"]
        }
    )
    print("Job submitted!")
    print("job name", resp["jobName"], "job ID", resp["jobId"])

submit_job() 関数について簡単に説明しよう. MNIST 手書き文字認識 (再訪) で, MNIST の Docker をローカルで実行したとき,次のようなコマンドを使用した.

sh
$ docker run -it mymnist --lr 0.1 --momentum 0.5 --epochs 10
$ docker run -it mymnist --lr 0.1 --momentum 0.5 --epochs 10

ここで, --lr 0.1 --momentum 0.5 --epochs 10 の部分が,コンテナに渡されるコマンドである.

AWS Batch でジョブを実行する際も,ContainerOverridescommand というパラメータを使用することで,コンテナに渡されるコマンドを指定することができる. コードでは以下の部分が該当する.

python
containerOverrides={
    "command": ["--lr", str(lr),
                "--momentum", str(momentum),
                "--epochs", str(epochs),
                "--uploadS3", "true"]
}
containerOverrides={
    "command": ["--lr", str(lr),
                "--momentum", str(momentum),
                "--epochs", str(epochs),
                "--uploadS3", "true"]
}

続いて, [4] 番のセルに移ろう. ここでは,上記の submit_job() 関数を用いて, 学習率 = 0.01, モメンタム=0.1, エポック数=100 を指定したジョブを投入する.

python
# [4]
submit_job(0.01, 0.1, 100)
# [4]
submit_job(0.01, 0.1, 100)

AWS の認証情報は, Jupyter Notebook の内部から再度定義する必要がある. これを手助けするため, Notebook の [2] 番のセル (デフォルトではすべてコメントアウトされている) を用意した. これを使うにはコメントアウトを解除すればよい. このセルを実行すると, AWS の認証情報を入力する対話的なプロンプトが表示される. プロンプトに従って aws secret key などを入力することで, (Jupyter のセッションに固有な) 環境変数に AWS の認証情報が記録される.

もう一つの認証方法として, submit_job() 関数に profile_name というパラメータを用意した. もし ~/.aws/credentials に認証情報が書き込まれているのならば (詳しくは (#aws_cli_install)), profile_name に使用したいプロファイルの名前を渡すだけで, 認証を行うことができる. 慣れている読者は後者のほうが便利であると感じるだろう.

[4] 番のセルを実行したら,ジョブが実際に投入されたかどうかを AWS コンソールから確認してみよう. AWS Batch の管理コンソールを開くと, figure_title のような画面が表示されるだろう.

AWS Batch でジョブが実行されている様子

figure_title で赤で囲った箇所に注目してほしい. 一つのジョブが投入されると,それは SUBMITTED という状態を経て RUNNABLE という状態に遷移する. RUNNABLE とは, ジョブを実行するためのインスタンスが Compute environment に不足しているため,新たなインスタンスが起動されるのを待っている状態に相当する. インスタンスの準備が整うと,ジョブの状態は STARTING を経て RUNNING に至る.

次に,ジョブのステータスが RUNNING のときの Compute environment の Desired vCPU を見てみよう (figure_title で紫で囲った箇所). ここで 4 と表示されているのは, g4dn.xlarge インスタンス一つ分の vCPU の数である. ジョブの投入に応じて,それを実行するのに最低限必要な EC2 インスタンスが起動されたことが確認できる (興味のある人は, EC2 コンソールも同時に覗いてみるとよい).

しばらく経つと,ジョブの状態は RUNNING から SUCCEEDED (あるいは何らかの理由でエラーが発生したときには FAILED) に遷移する. 今回のハンズオンで使っている MNIST の学習はだいたい 10 分くらいで完了するはずである. ジョブの状態が SUCCEEDED になるまで見届けよう.

ジョブが完了すると,学習の結果 (エポックごとの Loss と Accuracy を記録した CSV ファイル) は S3 に保存される. AWS コンソールからこれを確認しよう.

S3 のコンソールに行くと simplebatch-bucketXXXX (XXXX の部分はユーザーによって異なる) という名前のバケットが見つかるはずである. これをクリックして中身を見てみると, metrics_lr0.0100_m0.1000.csv という名前の CSV があることが確認できるだろう (figure_title). これが, 学習率 = 0.01, モメンタム = 0.1 として学習を行ったときの結果である.

ジョブの実行結果は S3 に保存される

さて,ここで run_single.ipynb に戻ってこよう. [5] から [7] 番のセルでは,学習結果の CSV ファイルのダウンロードを行っている.

python
# [5]
import pandas as pd
import io
from matplotlib import pyplot as plt

# [6]
def read_table_from_s3(bucket_name, key, profile_name=None):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    s3 = session.resource("s3")
    bucket = s3.Bucket(bucket_name)

    obj = bucket.Object(key).get().get("Body")
    df = pd.read_csv(obj)

    return df

# [7]
bucket_name = "simplebatch-bucket43879c71-mbqaltx441fu"
df = read_table_from_s3(
    bucket_name,
    "metrics_lr0.0100_m0.1000.csv"
)
# [5]
import pandas as pd
import io
from matplotlib import pyplot as plt

# [6]
def read_table_from_s3(bucket_name, key, profile_name=None):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    s3 = session.resource("s3")
    bucket = s3.Bucket(bucket_name)

    obj = bucket.Object(key).get().get("Body")
    df = pd.read_csv(obj)

    return df

# [7]
bucket_name = "simplebatch-bucket43879c71-mbqaltx441fu"
df = read_table_from_s3(
    bucket_name,
    "metrics_lr0.0100_m0.1000.csv"
)

[6] で S3 から CSV データをダウンロードし, pandas の DataFrame オブジェクトとしてロードする関数を定義している. [7] を実行する際, bucket_name という変数の値を,自分自身のバケットの名前に置き換えることに注意しよう (先ほど S3 コンソールから確認した simplebatch-bucketXXXX のことである).

続いて, [9] 番のセルで, CSV のデータをプロットしている (figure_title). ローカルで実行したときと同じように, AWS Batch を用いて MNIST モデルを訓練することに成功した!

python
# [9]
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(9,4))
x = [i for i in range(df.shape[0])]
ax1.plot(x, df["train_loss"], label="Train")
ax1.plot(x, df["val_loss"], label="Val")
ax2.plot(x, df["val_accuracy"])

ax1.set_xlabel("Epochs")
ax1.set_ylabel("Loss")
ax1.legend()

ax2.set_xlabel("Epochs")
ax2.set_ylabel("Accuracy")

print("Best loss:", df["val_loss"].min())
print("Best loss epoch:", df["val_loss"].argmin())
print("Best accuracy:", df["val_accuracy"].max())
print("Best accuracy epoch:", df["val_accuracy"].argmax())
# [9]
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(9,4))
x = [i for i in range(df.shape[0])]
ax1.plot(x, df["train_loss"], label="Train")
ax1.plot(x, df["val_loss"], label="Val")
ax2.plot(x, df["val_accuracy"])

ax1.set_xlabel("Epochs")
ax1.set_ylabel("Loss")
ax1.legend()

ax2.set_xlabel("Epochs")
ax2.set_ylabel("Accuracy")

print("Best loss:", df["val_loss"].min())
print("Best loss epoch:", df["val_loss"].argmin())
print("Best accuracy:", df["val_accuracy"].max())
print("Best accuracy epoch:", df["val_accuracy"].argmax())

AWS Batch で行った MNIST モデルの学習の結果

並列に複数の Job を実行する

さて,ここからが最後の仕上げである. ここまでのハンズオンで構築した AWS Batch のシステムを使って,ハイパーパラメータサーチを実際に行おう.

先ほど実行した run_single.ipynb と同じディレクトリにある run_sweep.ipynb を開く.

セル [1], [2], [3] は run_single.ipynb と同一である.

python
# [1]
import boto3
import argparse

# [2]
# AWS 認証ヘルパー ...省略...

# [3]
def submit_job(lr:float, momentum:float, epochs:int, profile_name=None):
    # ...省略...
# [1]
import boto3
import argparse

# [2]
# AWS 認証ヘルパー ...省略...

# [3]
def submit_job(lr:float, momentum:float, epochs:int, profile_name=None):
    # ...省略...

セル [4] の for ループを使って,グリッド状にハイパーパラメータの組み合わせを用意し, batch にジョブを投入している. ここでは 3x3=9 個のジョブを作成した.

python
# [4]
for lr in [0.1, 0.01, 0.001]:
    for m in [0.5, 0.1, 0.05]:
        submit_job(lr, m, 100)
# [4]
for lr in [0.1, 0.01, 0.001]:
    for m in [0.5, 0.1, 0.05]:
        submit_job(lr, m, 100)

セル [4] を実行したら, Batch のコンソールを開こう. 先ほどと同様に,ジョブのステータスは SUBMITTED > RUNNABLE > STARTING > RUNNING と移り変わっていくことがわかるだろう. 最終的に 9 個のジョブがすべて RUNNING の状態になることを確認しよう (figure_title). また,このとき Compute environment の Desired vCPUs は 4x9=36 となっていることを確認しよう (figure_title).

複数のジョブを同時投入したときの Batch コンソール

次に,Batch のコンソールの左側のメニューから Jobs をクリックしてみよう. ここでは,実行中のジョブの一覧が確認することができる (figure_title). ジョブのステータスでフィルタリングをすることも可能である. 9 個のジョブがどれも RUNNING 状態にあることが確認できるだろう.

複数のジョブを同時投入したときの Job 一覧

今度は EC2 コンソールを見てみよう. 左のメニューから Instances を選択すると, figure_title に示すような起動中のインスタンスの一覧が表示される. g4dn.xlarge が 9 台稼働しているのが確認できる. Batch がジョブの投下に合わせて必要な数のインスタンスを起動してくれたのだ!

複数のジョブを同時投入したときの EC2 インスタンスの一覧

ここまで確認できたら,それぞれの Job が終了するまでしばらく待とう (だいたい 10-15 分くらいで終わる). すべてのジョブが終了すると,ダッシュボードの SUCCEEDED が 9 となっているはずだ. また, Compute environment の Desired vCPUs も 0 に落ちていることを確認しよう. 最後に EC2 コンソールに行って,すべての g4dn インスタンスが停止していることを確認しよう.

以上から, AWS Batch を使うことで,ジョブの投入に応じて自動的に EC2 インスタンスが起動され,ジョブの完了とともに,ただちにインスタンスの停止が行われる一連の挙動を観察することができた. 一つのジョブの完了におよそ 10 分の時間がかかるので,9 個のハイパーパラメータの組を逐次的に計算していた場合は 90 分の時間を要することになる. AWS Batch を使ってこれらの計算を並列に実行することで,ジョブ一個分の計算時間 (=10 分) ですべての計算を終えることができた!

さて,再び run_sweep.ipynb に戻ってこよう. [5] 以降のセルでは,グリッドサーチの結果を可視化している.

python
# [5]
import pandas as pd
import numpy as np
import io
from matplotlib import pyplot as plt

# [6]
def read_table_from_s3(bucket_name, key, profile_name=None):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    s3 = session.resource("s3")
    bucket = s3.Bucket(bucket_name)

    obj = bucket.Object(key).get().get("Body")
    df = pd.read_csv(obj)

    return df

# [7]
grid = np.zeros((3,3))
for (i, lr) in enumerate([0.1, 0.01, 0.001]):
    for (j, m) in enumerate([0.5, 0.1, 0.05]):
        key = f"metrics_lr{lr:0.4f}_m{m:0.4f}.csv"
        df = read_table_from_s3("simplebatch-bucket43879c71-mbqaltx441fu", key)
        grid[i,j] = df["val_accuracy"].max()

# [8]
fig, ax = plt.subplots(figsize=(6,6))
ax.set_aspect('equal')

c = ax.pcolor(grid, edgecolors='w', linewidths=2)

for i in range(3):
    for j in range(3):
        text = ax.text(j+0.5, i+0.5, f"{grid[i, j]:0.1f}",
                       ha="center", va="center", color="w")
# [5]
import pandas as pd
import numpy as np
import io
from matplotlib import pyplot as plt

# [6]
def read_table_from_s3(bucket_name, key, profile_name=None):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    s3 = session.resource("s3")
    bucket = s3.Bucket(bucket_name)

    obj = bucket.Object(key).get().get("Body")
    df = pd.read_csv(obj)

    return df

# [7]
grid = np.zeros((3,3))
for (i, lr) in enumerate([0.1, 0.01, 0.001]):
    for (j, m) in enumerate([0.5, 0.1, 0.05]):
        key = f"metrics_lr{lr:0.4f}_m{m:0.4f}.csv"
        df = read_table_from_s3("simplebatch-bucket43879c71-mbqaltx441fu", key)
        grid[i,j] = df["val_accuracy"].max()

# [8]
fig, ax = plt.subplots(figsize=(6,6))
ax.set_aspect('equal')

c = ax.pcolor(grid, edgecolors='w', linewidths=2)

for i in range(3):
    for j in range(3):
        text = ax.text(j+0.5, i+0.5, f"{grid[i, j]:0.1f}",
                       ha="center", va="center", color="w")

最終的に出力されるプロットが figure_title である.

ハイパーパラメータのグリッドサーチの結果

このプロットから,差は僅かであるが,学習率が 0.1 のときに精度は最大となることがわかる. また,学習率 0.1 のときはモメンタムを変えても大きな差は生じないことが見て取れる.

今回のパラメータサーチは勉強用に極めて単純化されたものである点は承知いただきたい.

たとえば,今回は学習率が 0.1 が最も良いとされたが,それは訓練のエポックを 100 に限定しているからかもしれない. 学習率が低いとその分訓練に必要なエポック数も多くなる. 訓練のエポック数をもっと増やせばまた違った結果が観察される可能性はある.

また,今回は MNIST の訓練データ 60,000 枚のうち, 48,000 枚を訓練データ,残り 12,000 枚を検証データとして用いた. この分割は乱数を固定してランダムに行ったが,もしこの分割によるデータのバイアスを気にするならば, k 個の異なる学習・検証データの分割をあらかじめ用意して,複数回モデルの評価を行う (k-fold cross-validation) 方法も,より精緻なアプローチとして考えられる.

以上のようにして, CNN を用いた MNIST 分類モデルのハイパーパラメータの最適化の一連の流れを体験した. AWS Batch を利用することで,比較的少ないプログラミングで,動的に EC2 クラスターを制御し,並列にジョブを処理するシステムが構築できた. ここまで EC2 を使いこなすことができれば,多くの問題を自力で解くことが可能になるだろう!

スタックの削除

これにて,本ハンズオンは終了である.最後にスタックを削除しよう. 今回のスタックを削除するにあたり,ECR に配置された Docker のイメージは手動で削除されなければならない (これをしないと, cdk destroy を実行したときにエラーになってしまう. これは CloudFormation の仕様なので従うしかない).

ECR の Docker image を削除するには, ECR のコンソールに行き,イメージが配置されたレポジトリを開く. そして,画面右上の DELETE ボタンを押して削除する (figure_title).

ECR から Docker image を削除する

あるいは, AWS CLI から同様の操作を行うには,以下のコマンドを用いる (XXXX は自分の ECR レポジトリ名に置き換える).

sh
$ aws ecr batch-delete-image --repository-name XXXX --image-ids imageTag=latest
$ aws ecr batch-delete-image --repository-name XXXX --image-ids imageTag=latest

image の削除が完了したうえで,次のコマンドでスタックを削除する.

sh
$ cdk destroy
$ cdk destroy

(#sec:batch_development_and_debug) === クラウドを用いた機械学習アプリケーションの開発とデバッグ

本章で紹介したハンズオンでは, AWS Batch を使用することでニューラルネットの学習を複数並列に実行し,高速化を実現した. 本章の最後の話題として,クラウドを用いた機械学習アプリケーションの開発とデバッグの方法について述べよう.

ローカルに GPU を搭載した強力なマシンがなく,クラウドを利用する予算が確保されているのであれば, figure_title のような開発のスキームが理想的であると考える. 最初の段階では, (#sec_jupyter_and_deep_learning) で見たような方法で, GPU 搭載型の EC2 インスタンスを作成し, Jupyter Notebook などのインタラクティブな環境で様々なモデルを試し実験を行う. Jupyter である程度アプリケーションが完成してきたタイミングで,作成したアプリケーションを Docker イメージにパッケージングする. そして, EC2 上で docker run を行い,作成したイメージがバグなく動作するか確認を行う. その次に,ハイパーパラメータの最適化などのチューニングを, Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する のハンズオンで学んだ AWS Batch などの計算システムを利用して行う. よい深層学習モデルが完成したら,仕上げに大規模データへの推論処理を行うシステムを (#sec_fargate_qabot) を参考に構築する.

実際,本書ではこの流れに沿って演習を進めてきた. MNIST タスクを解くモデルを,最初 Jupyter Notebook を使用して実験し,そのコードをほとんどそのまま Docker にパッケージし, AWS Batch を用いてハイパーパラメータサーチを行った. このサイクルを繰り返すことで,クラウドを最大限に活用した機械学習アプリケーションの開発を進めることができる.

クラウドを活用した機械学習アプリケーションの開発フロー

小括

ここまでが,本書第二部の内容である. 第一部に引き続き盛りだくさんの内容であったが,ついてこれたであろうか?

第二部ではまず最初に,深層学習の計算をクラウドで実行するため, GPU 搭載型の EC2 インスタンスの起動について解説した. さらに,ハンズオンでは,クラウドに起動した仮想サーバーを使って MNIST 文字認識タスクを解くニューラルネットを訓練した ( (#sec_jupyter_and_deep_learning)).

また,より大規模な機械学習アプリケーションを作るための手段として, Docker と ECS によるクラスターの初歩を説明した ( (#sec_docker_introduction)). その応用として,英語で与えられた文章問題への回答を自動で生成するボットをクラウドに展開した ( (#sec_fargate_qabot)). タスクの投入に応じて動的に計算リソースが作成・削除される様子を実際に体験できただろう.

さらに, Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する では AWS Batch を用いてニューラルネットの学習を並列に実行する方法を紹介した. ここで紹介した方法は,ミニマムであるが,計算機システムを大規模化していくためのエッセンスが網羅されている. これらのハンズオン体験から,クラウド技術を応用してどのように現実世界の問題を解いていくのか,なんとなくイメージが伝わっただろうか?

本書の第三部では,さらにレベルアップし,サーバーレスアーキテクチャという最新のクラウドの設計手法について解説する. その応用として,ハンズオンでは簡単な SNS サービスをゼロから実装する. 引き続きクラウドの最先端の世界を楽しんでいこう!

]]>
Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する

ハンズオン第三回では, ECS と Fargate を使って自動質問回答システムを構築した. シンプルながらも,複数の質問が送られた場合には並列にジョブが実行され,ユーザーに答えが返されるシステムを作ることができた. ここでは,すでに学習済みの言語モデルを用いてアプリケーションを構築した. しかし,一般的に言って,機械学習のワークフローでは自分で作ったモデルを訓練することが最初のステップにあるはずである. そこで,ハンズオン第四回では,クラウドを用いて機械学習の訓練を並列化・高速化することを考える.

本ハンズオンでは深層学習におけるハイパーパラメータ最適化を取り上げる. ハイパーパラメータとは,勾配降下法によって最適化されるニューラルネットのパラメータの外にあるパラメータのことであり,具体的にはモデルの層の幅・深さなどネットワークのアーキテクチャに関わるもの,学習率やモメンタムなどパラメータの更新則に関わるものなどが含まる. 深層学習においてハイパーパラメータの調整はとても重要なタスクである. しかしながら,ハイパーパラメータを調整するには,少しずつ条件を変えながら何度もニューラルネットを学習させる必要があり,多くの計算時間がかかる. 研究・開発においては,スループットよくたくさんのモデルの可能性を探索することが生産性を決める重要なファクターであり,ハイパーパラメータ探索を高速に解くという問題は極めて関心が高い. 本ハンズオンでは,クラウドの強力な計算リソースを利用して並列的にニューラルネットの訓練を実行することで,この問題を解く方法を学んでいこう.

Auto scaling groups (ASG)

ハンズオンに入っていく前に, Auto scaling groups (ASG) とよばれる EC2 の概念を知っておく必要がある.

ECS の概要を示した (#ecs_overview) を振り返って見てほしい. 前章 ( (#sec_fargate_qabot)) でも説明したが, ECS のクラスターで計算を担う実体としては EC2 と Fargate を指定することができる. Fargate については前章で記述した. Fargate を用いると,自在にスケールする計算環境をとても簡単な設定で構築することができた. しかし, GPU を利用することができないなど,いくつかの制約があった. EC2 を使用した計算環境を指定することで,プログラミングの複雑度は増すが, GPU やその他のより高度かつ複雑な設定を伴ったクラスターを構築することができる.

EC2 クラスターには ASG と呼ばれるサービスが配置される. ASG は複数の EC2 インスタンスをロジカルな単位でグループ化することでクラスターを構成する. ASG はクラスター内に新しいインスタンスを起動する,あるいは不要になったインスタンスを停止するなどのスケーリングを担う. ASG で重要な概念として, desired capacity, minimum capacity, maximum capacity というパラメータがある. minimum capacity, maximum capacity は,それぞれクラスター内に配置できるインスタンスの数の最小値・最大値を指定するパラメータである. 前者は,クラスターに負荷がかかっていない場合でもアイドリング状態にあるインスタンスを維持することで,急に負荷が増大した時などのバッファーとして作用することができる. 後者は,負荷が急に増えたときに,過剰な数のインスタンスが起動する事態を防ぎ,経済的なコストの上限を定める役割を果たす.

desired capacity が,その時々でシステムが要求するインスタンスの数を指定する. desired capacity は,例えば 24 時間のリズムに合わせてインスタンスの数を増減させる (昼は多く夜は少なくなど) などの決まったスケジュールに基づいた設定を適用することができる. あるいはクラスター全体にかかっている負荷に応じて, desired capacity を動的に制御することも可能である. どのような基準でクラスターのスケーリングを行うかを定めるルールのことを,スケーリングポリシーとよぶ. たとえば,クラスター全体の稼働率 (負荷) を常に 80% に維持する,などのスケーリングポリシーが想定できる. この場合,クラスター全体の負荷が 80%を下回ったときにはクラスターからインスタンスが削除され,80%を超える (あるいは超えると予測される) 場合はインスタンスを追加する,という操作が ASG によって自動的に行われる.

上記のようなパラメータを検討し,ユーザーは ASG を作成する. ASG を作成したのち, ECS との連携をプログラムしてあげることで, ECS を介して ASG による EC2 クラスターにタスクを投入することが可能になる.

AWS Batch

AWS Batch のアイコン

先に説明したように, ECS と ASG を組み合わせることで,所望の計算クラスターを構築することが可能である. しかしながら, ECS と ASG にはかなり込み入った設定が必要であり,初心者にとっても経験者にとってもなかなか面倒なプログラミングが要求される. そこで, ECS と ASG によるクラスターの設計を自動化してくれるサービスが提供されている. それが AWS Batch である.

AWS Batch はその名のとおりバッチ (Batch) 化されたジョブ (入力データだけが異なる独立した演算が繰り返し実行されること) を想定している. 多くの科学計算や機械学習がバッチ計算に当てはまる. たとえば,初期値のパラメータを変えて複数のシミュレーションを走らせる,といったケースだ. AWS Batch を用いることの利点は,クラスターのスケーリングやジョブの割り振りはすべて自動で実行され, ユーザーはクラウドの舞台裏の詳細を気にすることなく,大量のジョブを投入できるシステムが手に入る点である. が,知識として背後では ECS/ASG/EC2 の三つ巴が協調して動作しているという点は知っておいてほしい.

AWS Batch では,ジョブの投入・管理をスムーズに行うため,次のような概念が定義されている (figure_title). まず, ジョブ (Job) というのが,AWS Batch によって実行される一つの計算の単位である. Job definitions とはジョブの内容を定義するものであり,これには実行されるべき Docker のイメージのアドレスや,割り当てる CPU・RAM の容量,環境変数などの設定が含まれる. Job definition に基づいて個々のジョブが実行される. ジョブが実行されると,ジョブは Job queues に入る. Job queues とは,実行待ち状態にあるジョブの列のことであり,時間的に最も先頭に投入されたジョブが最初に実行される. また,複数の queue を配置し, queue ごとに priority (優先度) を設定することが可能であり, priority の高い queue に溜まったジョブが優先的に実行される (筆者はこれをディズニーランドの"ファストパス"を連想して捉えている). Compute environment とは,先述したクラスターとほぼ同義の概念であり,計算が実行される場所 (EC2 や Fargate からなるクラスター) を指す. Compute environment には,使用する EC2 のインスタンスタイプや同時に起動するインスタンス数の上限などの簡易なスケーリングポリシーが指定されている. Job queues は Compute environment の空き状況を監視しており, それに応じてジョブを Compute environment に投下する.

以上が AWS Batch を使用するうえで理解しておかなければならない概念であるが,くどくど言葉で説明してもなかなかピンとこないだろう. ここからは,実際に自分で手を動かしながら学んでいこう.

AWS Batch の主要な概念

EC2 or Fargate?

ECS でクラスターを構成する際,計算を実行する場として EC2 と Fargate の二つの選択肢があることを説明した. それぞれ長所と短所を抱えているのだが,どのような場合にどちらを使うべきだろうか? それを検討するため,まずは table_title を見てみよう. これは EC2 と Fargate の特徴をまとめたものである. 説明の都合上,大幅な粗視化が行われている点は留意していただきたい.

EC2 vs Fargate
EC2Fargate

Compute capacity

Medium to large

Small to medium

GPU

Yes

No

Launch speed

Slow

Fast

Task placement flexibility

Low

High

Programming complexity

High

Low

これまでに見てきたように, EC2 は最大の CPU 数・メモリーサイズが大きかったり, GPU を利用できたりするなど,単一のインスタンスでの計算能力は高い. 対して, Fargate は単一インスタンスの最大 CPU 数は 4 コアが上限である. その一方で,インスタンスの起動に要する時間は Fargate のほうが圧倒的に早く,より俊敏にクラスターのスケーリングを行うことができる. また,タスクをクラスターに投入する際のフレキシビリティも Fargate のほうが高い. フレキシビリティというのは,例えば一つのインスタンスで 2 つ以上のコンテナを走らせる,などの状況である. 単位 CPU あたりで処理されるタスクの数を最大化する際には,このような設計がしばしば採用される. プログラミングの複雑さという観点からは, Fargate のほうが一般的にシンプルな実装になる.

このように, EC2 と Fargate は互いに相補的な特性を有しており,アプリケーションによって最適な計算環境は検討される必要がある. また,EC2 と Fargate を両方用いたハイブリッドクラスターというのも定義可能であり,そのような選択肢もしばしば用いられる.

準備

ハンズオンのソースコードは GitHub の handson/aws-batch にある.

本ハンズオンの実行には,第一回ハンズオンで説明した準備 ( (#handson_01_prep)) が整っていることを前提とする. また, Docker が自身のローカルマシンにインストール済みであることも必要である.

このハンズオンは, g4dn.xlarge タイプの EC2 インスタンスを使うので,アメリカ東部 (us-east-1) リージョンでは 0.526 $/hour のコストが発生する. 東京 (ap-northeast-1) を選択した場合は 0.71 $/hour のコストが発生する.

(#sec:jupyter_and_deep_learning_setup) でも注意したが,このハンズオンを始める前に G タイプインスタンスの起動上限を AWS コンソールの EC2 管理画面から確認しよう. もし上限が 0 になっていた場合は,上限緩和の申請を行う必要がある. アプリケーションの説明 にも関連した情報を記載しているので,併せて参照されたい.

MNIST 手書き文字認識 (再訪)

今回のハンズオンでは,機械学習のハイパーパラメータ調整を取り上げると冒頭で述べた. その最もシンプルな例題として, (#sec_mnist_using_jupyter) で扱った MNIST 手書き文字認識の問題を再度取り上げよう. (#sec_mnist_using_jupyter) では,適当にチョイスしたハイパーパラメータを用いてモデルの訓練を行った. ここで使用したプログラムのハイパーパラメータとしては,確率的勾配降下法 (SGD) における学習率やモメンタムが含まれる. コードでいうと,次の行が該当する.

python
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)

ここで使用された 学習率 (lr=0.01) やモメンタム (momentum=0.5) は恣意的に選択された値であり,これがベストな数値であるのかはわからない. たまたまこのチョイスが最適であるかもしれないし,もっと高い精度を出すハイパーパラメータの組が存在するかもしれない. この問題に答えるため,ハイパーパラメータサーチを行おう. 今回は,最もシンプルなアプローチとして,グリッドサーチによるハイパーパラメータサーチを行おう.

機械学習のハイパーパラメータの最適化には大きく3つのアプローチが挙げられる. グリッドサーチ,ランダムサーチ,そしてベイズ最適化による方法である.

グリッドサーチとは,ハイパーパラメータの組をある範囲の中で可能な組み合わせをすべて計算し,最適なパラメータの組を見出す方法である. 最もシンプルかつ確実な方法であるが,すべての組み合わせの可能性を愚直に計算するので計算コストが大きい.

ランダムサーチ法とは,ハイパーパラメータの組をある範囲の中でランダムに抽出し,大量に試行されたランダムな組の中から最適なパラメータの組を見出す方法である. すべての可能性を網羅的に探索できるわけではないが,調整すべきパラメータの数が多数ある場合に,グリッドサーチよりも効率的に広い探索空間をカバーすることができる.

ベイズ最適化を用いた方法では,過去の探索結果から次にどの組み合わせを探索すべきかという指標を計算し,次に探索するパラメータを決定する. これにより,理論的にはグリッドサーチやランダムサーチ法よりも少ない試行回数で最適なパラメータにたどり着くことができる.

並列化の観点でいうと,グリッドサーチとランダムサーチは各ハイパーパラメータの組の計算は独立に実行することができるため並列化が容易である. このように独立したジョブとして分割・並列化可能な問題を Embarrassingly parallel な問題とよぶ (直訳すると"恥ずかしいほど並列化可能な問題",ということになる). Embarrassingly parallel な問題はクラウドの強力な計算リソースを用いることで,非常なシンプルな実装で解くことができる. この章ではこのようなタイプの並列計算を取り上げる.

一方,ベイズ最適化による方法は,過去の結果をもとに次の探索が決定されるので,並列化はそれほど単純ではない. 最近では optuna などのハイパーパラメータ探索のためのライブラリが発達しており,ベイズ最適化の数理的な処理を自動で実行してくれるので便利である. これらのライブラリを使うと,もし一台のコンピュータ (ノード) の中に複数の GPU が存在する場合は,並列に計算を実行することができる. しかしながら,一台のノードにとどまらず,複数のノードをまたいだ並列化は,高度なプログラミングテクニックが必要とされるだけでなく,ノード間の接続様式などクラウドのアーキテクチャにも深く依存するものである. 本書ではここまで高度なクラウドの使用方法には立ち入らない.

まずは,本ハンズオンで使用する Docker イメージをローカルで実行してみよう.

Docker イメージのソースコードは handson/aws-batch/docker にある. 基本的に (#sec_mnist_using_jupyter) のハンズオンを元にし,本ハンズオン専用の軽微な変更が施してある. 興味のある読者はソースコードも含めて読んでいただきたい.

練習として,この Docker イメージを手元でビルドするところからはじめてみよう. Dockerfile が保存されているディレクトリに移動し, mymnist という名前 (Tag) をつけてビルドを実行する.

sh
$ cd handson/aws-batch/docker
$ docker build -t mymnist .
$ cd handson/aws-batch/docker
$ docker build -t mymnist .

docker build でエラーが出たときは次の可能性を疑ってほしい. ビルドの中で, MNIST の画像データセットを http://yann.lecun.com/exdb/mnist/ からダウンロードするのだが,ダウンロード先のサーバーがしばしばダウンしている. 世界中の機械学習ユーザーがアクセスするので,これはしばしば発生するようである. サーバーがダウンしているとビルドも失敗してしまう. エラーメッセージにそれらしい文言が含まれていたら,この可能性を疑おう.

手元でビルドするかわりに, Docker Hub から pull することも可能である. その場合は次のコマンドを実行する.

sh
$ docker pull tomomano/mymnist:latest
$ docker pull tomomano/mymnist:latest

イメージの準備ができたら,次のコマンドでコンテナを起動し, MNIST の学習を実行する..

sh
$ docker run mymnist --lr 0.1 --momentum 0.5 --epochs 10
$ docker run mymnist --lr 0.1 --momentum 0.5 --epochs 10

このコマンドを実行すると,指定したハイパーパラメータ (--lr で与えられる学習率と --momentum で与えられるモメンタム) を使ってニューラルネットの最適化が始まる. 学習を行う最大のエポック数は --epochs パラメータで指定する. (#sec_jupyter_and_deep_learning) のハンズオンで見たような, Loss の低下がコマンドライン上に出力されるだろう (figure_title).

Docker を実行した際の出力

上に示したコマンドを使うと,計算は CPU を使って実行される. もし,ローカルの計算機に GPU が備わっており, nvidia-docker の設定が済んでいるならば, 次のコマンドにより GPU を使って計算を実行できる.

$ docker run --gpus all mymnist --lr 0.1 --momentum 0.5 --epochs 10

このコマンドでは,--gpus all というパラメータが加わった.

CPU/GPU どちらで実行した場合でも,エポックを重ねるにつれて訓練データ (Train データ) の Loss は単調に減少していくのが見て取れるだろう. 一方,検証データ (Validation データ) の Loss および Accuracy は,ある程度まで減少した後,それ以上性能が向上しないことに気がつくだろう. これを実際にプロットしてみると figure_title のようになるはずである.

(左) Train/Validation データそれぞれの Loss のエポックごとの変化. (右) Validation データの Accuracy のエポックごとの変化

これはオーバーフィッティングとよばれる現象で,ニューラルネットが訓練データに過度に最適化され,訓練データの外のデータに対しての精度 (汎化性能) が向上していないことを示している. このような場合の対処法として, Early stopping とよばれるテクニックが知られている. Early stopping とは,検証データの Loss を追跡し,それが減少から増加に転じるエポックで学習をうち止め,そのエポックでのウェイトパラメータを採用する,というものである. 本ハンズオンでも, Early stopping によって訓練の終了を判断し,モデルの性能評価を行っていく.

MNIST 手書き文字データセットでは,訓練データとして 60,000 枚,テストデータとして 10,000 枚の画像が与えられている. 本ハンズオンで使用するコードでは,訓練データのうち 80% の 48,000 枚を訓練データとして使用し,残り 20% の 12,000 枚を検証データとして用いている. 詳しくはソースコードを参照のこと.

アプリケーションの説明

このハンズオンで作成するアプリケーションの概要を figure_title に示す.

アプリケーションのアーキテクチャ

簡単にまとめると,次のような設計である.

  • クライアントは,あるハイパーパラメータの組を指定して Batch にジョブを提出する

  • Batch はジョブを受け取ると, EC2 からなるクラスターで計算を実行する

  • クラスター内では g4dn.xlarge インスタンスが起動する

  • Docker イメージは, AWS 内に用意された ECR (Elastic Container Registry) から取得される

  • 複数のジョブが投下された場合は,その数だけのインスタンスが起動し並列に実行される

  • 各ジョブによる計算の結果は S3 に保存される

  • 最後にクライアントは S3 から結果をダウンロードし,最適なハイパーパラメータの組を決定する

それでは,プログラムのソースコードを見てみよう (handson/aws-batch/app.py).

python
class SimpleBatch(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        bucket = s3.Bucket(
            self, "bucket",
            removal_policy=core.RemovalPolicy.DESTROY,
            auto_delete_objects=True,
        )

        vpc = ec2.Vpc(
            self, "vpc",
            # other parameters...
        )

        #
        managed_env = batch.ComputeEnvironment(
            self, "managed-env",
            compute_resources=batch.ComputeResources(
                vpc=vpc,
                allocation_strategy=batch.AllocationStrategy.BEST_FIT,
                desiredv_cpus=0,
                maxv_cpus=64,
                minv_cpus=0,
                instance_types=[
                    ec2.InstanceType("g4dn.xlarge")
                ],
            ),
            managed=True,
            compute_environment_name=self.stack_name + "compute-env"
        )

        #
        job_queue = batch.JobQueue(
            self, "job-queue",
            compute_environments=[
                batch.JobQueueComputeEnvironment(
                    compute_environment=managed_env,
                    order=100
                )
            ],
            job_queue_name=self.stack_name + "job-queue"
        )

        #
        job_role = iam.Role(
            self, "job-role",
            assumed_by=iam.CompositePrincipal(
                iam.ServicePrincipal("ecs-tasks.amazonaws.com")
            )
        )
        # allow read and write access to S3 bucket
        bucket.grant_read_write(job_role)

        #
        repo = ecr.Repository(
            self, "repository",
            removal_policy=core.RemovalPolicy.DESTROY,
        )

        #
        job_def = batch.JobDefinition(
            self, "job-definition",
            container=batch.JobDefinitionContainer(
                image=ecs.ContainerImage.from_ecr_repository(repo),
                command=["python3", "main.py"],
                vcpus=4,
                gpu_count=1,
                memory_limit_mib=12000,
                job_role=job_role,
                environment={
                    "BUCKET_NAME": bucket.bucket_name
                }
            ),
            job_definition_name=self.stack_name + "job-definition",
            timeout=core.Duration.hours(2),
        )
class SimpleBatch(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        bucket = s3.Bucket(
            self, "bucket",
            removal_policy=core.RemovalPolicy.DESTROY,
            auto_delete_objects=True,
        )

        vpc = ec2.Vpc(
            self, "vpc",
            # other parameters...
        )

        #
        managed_env = batch.ComputeEnvironment(
            self, "managed-env",
            compute_resources=batch.ComputeResources(
                vpc=vpc,
                allocation_strategy=batch.AllocationStrategy.BEST_FIT,
                desiredv_cpus=0,
                maxv_cpus=64,
                minv_cpus=0,
                instance_types=[
                    ec2.InstanceType("g4dn.xlarge")
                ],
            ),
            managed=True,
            compute_environment_name=self.stack_name + "compute-env"
        )

        #
        job_queue = batch.JobQueue(
            self, "job-queue",
            compute_environments=[
                batch.JobQueueComputeEnvironment(
                    compute_environment=managed_env,
                    order=100
                )
            ],
            job_queue_name=self.stack_name + "job-queue"
        )

        #
        job_role = iam.Role(
            self, "job-role",
            assumed_by=iam.CompositePrincipal(
                iam.ServicePrincipal("ecs-tasks.amazonaws.com")
            )
        )
        # allow read and write access to S3 bucket
        bucket.grant_read_write(job_role)

        #
        repo = ecr.Repository(
            self, "repository",
            removal_policy=core.RemovalPolicy.DESTROY,
        )

        #
        job_def = batch.JobDefinition(
            self, "job-definition",
            container=batch.JobDefinitionContainer(
                image=ecs.ContainerImage.from_ecr_repository(repo),
                command=["python3", "main.py"],
                vcpus=4,
                gpu_count=1,
                memory_limit_mib=12000,
                job_role=job_role,
                environment={
                    "BUCKET_NAME": bucket.bucket_name
                }
            ),
            job_definition_name=self.stack_name + "job-definition",
            timeout=core.Duration.hours(2),
        )
  • で,計算結果を保存するための S3 バケットを用意している

  • で, Compute environment を定義している. ここでは g4dn.xlarge のインスタンスタイプを使用するとし,最大の vCPU 使用数は 64 と指定している. また,最小の vCPU は 0 である. 今回は,負荷がかかっていないときにアイドリング状態にあるインスタンスを用意する利点は全くないので,ここは 0 にするのが望ましい.

  • で, <2> で作成した Compute environment と紐付いた Job queue を定義している.

  • で,ジョブが計算結果を S3 に書き込むことができるよう, IAM ロールを定義している. (IAM とはリソースがもつ権限を管理する仕組みである.詳しくは (#sec:bashoutter_iam) を参照)

  • では, Docker image を配置するための ECR を定義している.

  • で Job definition を作成している. ここでは,4 vCPU, 12000 MB (=12GB) の RAM を使用するように指定している. また,今後必要となる環境変数 (BUCKET_NAME) を設定している. さらに, <4> で作った IAM を付与している.

g4dn.xlarge は 1 台あたり 4 vCPU が割り当てられている. このプログラムでは Compute environment の maximum vCPUs を 64 と指定しているので,最大で 16 台のインスタンスが同時に起動することになる. ここで maxium vCPUs を 64 に限定しているのは,なんらかのミスで意図せぬジョブを大量にクラスターに投入してしまった事態で,高額の AWS 利用料金が発生するのを防ぐためである. もし,自分のアプリケーションで必要と判断したならば自己責任において 64 よりも大きな数を設定して構わない.

ここで注意が一点ある. AWS では各アカウントごとに EC2 で起動できるインスタンスの上限が設定されている. この上限は AWS コンソールにログインし, EC2 コンソールの左側メニューバーの Limits をクリックすることで確認できる (figure_title). g4dn.xlarge (EC2 の区分でいうと G ファミリーに属する) の制限を確認するには, Running On-Demand All G instances という名前の項目を見る. ここにある数字が, AWS によって課されたアカウントの上限であり,この上限を超えたインスタンスを起動することはできない. もし,自分の用途に対して上限が低すぎる場合は,上限の緩和申請を行うことができる. 詳しくは 公式ドキュメンテーション "Amazon EC2 service quotas" を参照のこと.

EC2コンソールから各種の上限を確認する

スタックのデプロイ

スタックの中身が理解できたところで,早速スタックをデプロイしてみよう.

デプロイの手順は,これまでのハンズオンとほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). シークレットキーの設定も忘れずに ( (#aws_cli_install)).

sh
# プロジェクトのディレクトリに移動
$ cd handson/aws-batch

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd handson/aws-batch

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイのコマンドが無事に実行されたことが確認できたら,AWS コンソールにログインして,デプロイされたスタックを確認してみよう. コンソールの検索バーで batch と入力し, AWS Batch の管理画面を開く (figure_title).

AWS Batch のコンソール画面 (ダッシュボード)

まず目を向けてほしいのが,画面の一番下にある Compute environment overview の中の SimpleBatchcompute-env という名前の項目だ. Compute environment とは,先ほど述べたとおり,計算が実行される環境 (クラスターと読み替えてもよい) である. プログラムで指定したとおり, g4dn.xlarge が実際に使用されるインスタンスタイプとして表示されている. また, Minimum vCPUs が 0,Maximum vCPUs が 64 と設定されていることも見て取れる. 加えて,この時点では一つもジョブが走っていないので, Desired vCPUs は 0 になっている. より詳細な Compute environment の情報を閲覧したい場合は,名前をクリックすることで詳細画面が開く.

次に,Job queue overview にある SimpleBatch-queue という項目に注目してほしい. ここでは実行待ちのジョブ・実行中のジョブ・実行が完了したジョブを一覧で確認することができる. PENDING, RUNNING, SUCCEEDED, FAILED などのカラムがあることが確認できる.ジョブが進行するにつれて,ジョブの状態がこのカラムにしたがって遷移していく. 後でジョブを実際にサブミットしたときに戻ってこよう.

最後に,今回作成した Job definition を確認しよう. 左側のメニューから Job definitions を選択し,次の画面で SimpleBatchjob-definition という項目を見つけて開く. ここから Job definition の詳細を閲覧することができる (figure_title). 中でも重要な情報としては, vCPUs, Memory, GPU がそれぞれ Docker に割り当てられる vCPU・メモリー・ GPU の量を規定している. また, Image と書いてあるところに,ジョブで使用される Docker イメージが指定されている. ここでは, ECR のレポジトリを参照している. 現時点ではこの ECR は空である. 次のステップとして,この ECR にイメージを配置する作業を行おう.

AWS Batch から Job definition を確認

Docker image を ECR に配置する

さて, Batch がジョブを実行するには,どこか指定された場所から Docker イメージをダウンロード (pull) してくる必要がある. 前回のハンズオン ( (#sec_fargate_qabot)) では,公開設定にしてある Docker Hub からイメージを pull してきた. 今回のハンズオンでは, AWS から提供されているレジストリである ECR (Elastic Container Registry) に image を配置するという設計を採用する. ECR を利用する利点は,自分だけがアクセスすることのできるプライベートなイメージの置き場所を用意できる点である. Batch は ECR からイメージを pull してくることで,タスクを実行する (figure_title).

スタックのソースコードでいうと,次の箇所が ECR を定義している.

python
#
repo = ecr.Repository(
    self, "repository",
    removal_policy=core.RemovalPolicy.DESTROY,
)

job_def = batch.JobDefinition(
    self, "job-definition",
    container=batch.JobDefinitionContainer(
        image=ecs.ContainerImage.from_ecr_repository(repo), #
        ...
    ),
    ...
)
#
repo = ecr.Repository(
    self, "repository",
    removal_policy=core.RemovalPolicy.DESTROY,
)

job_def = batch.JobDefinition(
    self, "job-definition",
    container=batch.JobDefinitionContainer(
        image=ecs.ContainerImage.from_ecr_repository(repo), #
        ...
    ),
    ...
)
  • で,新規の ECR を作成している.

  • で Job definition を定義する中で,イメージを <1> で作った ECR から取得するように指定している. これと同時に, Job definition には ECR へのアクセス権限が IAM を通じて自動的に付与される.

さて,スタックをデプロイした時点では, ECR は空っぽである. ここに自分のアプリケーションで使う Docker イメージを push してあげる必要がある.

そのために,まずは AWS コンソールから ECR の画面を開こう (検索バーに Elastic Container Registry と入力すると出てくる). Private というタブを選択すると, simplebatch-repositoryXXXXXX という名前のレポジトリが見つかるだろう (figure_title).

ECR のコンソール画面

次に,このレポジトリの名前をクリックするとレポジトリの詳細画面に遷移する. そうしたら,画面右上にある View push commands というボタンをクリックする. すると figure_title のようなポップアップ画面が立ち上がる.

ECR への push コマンド

このポップアップ画面で表示されている四つのコマンドを順番に実行していくことで,手元の Docker イメージを ECR に push することができる. push を実行する前に, AWS の認証情報が設定されていることを確認しよう. そのうえで,ハンズオンのソースコードの中にある docker/ という名前のディレクトリに移動する. そうしたら,ポップアップ画面で表示されたコマンドを上から順に実行していく.

ポップアップで表示されるコマンドの 2 つめを見てみると docker build -t XXXXX . となっている. 最後の . が重要で,これは 現在のディレクトリにある Dockerfile を使ってイメージをビルドせよ という意味である. このような理由で, Dockerfile が置いてあるディレクトリに移動する必要がある.

四つ目のコマンドは,数 GB あるイメージを ECR にアップロードするので少し時間がかかるかもしれないが,これが完了するとめでたくイメージが ECR に配置されたことになる. もう一度 ECR のコンソールを見てみると,確かにイメージが配置されていることが確認できる (figure_title). これで,AWS Batch を使ってジョブを実行させるための最後の準備が完了した.

ECR へ image の配置が完了した

単一のジョブを実行する

さて,ここからは実際に AWS Batch にジョブを投入する方法を見ていこう.

ハンズオンのディレクトリの notebook/ というディレクトリの中に, run_single.ipynb というファイルが見つかるはずである (.ipynb は Jupyter notebook のファイル形式). これを Jupyter notebook から開こう.

今回のハンズオンでは, venv による仮想環境の中に Jupyter notebook もインストール済みである. なので,ローカルマシンから以下のコマンドで Jupyter notebook を立ち上げる.

sh
# .env の仮想環境にいることを確認
(.env) $ cd notebook
(.env) $ jupyter notebook
# .env の仮想環境にいることを確認
(.env) $ cd notebook
(.env) $ jupyter notebook

Jupyter notebook が起動したら, run_single.ipynb を開く.

最初の [1], [2], [3] 番のセルは,ジョブをサブミットするための関数 (submit_job()) を定義している.

python
# [1]
import boto3
import argparse

# [2]
# AWS 認証ヘルパー ...省略...

# [3]
def submit_job(lr:float, momentum:float, epochs:int, profile_name="default"):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    client = session.client("batch")

    title = "lr" + str(lr).replace(".", "") + "_m" + str(momentum).replace(".", "")
    resp = client.submit_job(
        jobName=title,
        jobQueue="SimpleBatchjob-queue",
        jobDefinition="SimpleBatchjob-definition",
        containerOverrides={
            "command": ["--lr", str(lr),
                        "--momentum", str(momentum),
                        "--epochs", str(epochs),
                        "--uploadS3", "true"]
        }
    )
    print("Job submitted!")
    print("job name", resp["jobName"], "job ID", resp["jobId"])
# [1]
import boto3
import argparse

# [2]
# AWS 認証ヘルパー ...省略...

# [3]
def submit_job(lr:float, momentum:float, epochs:int, profile_name="default"):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    client = session.client("batch")

    title = "lr" + str(lr).replace(".", "") + "_m" + str(momentum).replace(".", "")
    resp = client.submit_job(
        jobName=title,
        jobQueue="SimpleBatchjob-queue",
        jobDefinition="SimpleBatchjob-definition",
        containerOverrides={
            "command": ["--lr", str(lr),
                        "--momentum", str(momentum),
                        "--epochs", str(epochs),
                        "--uploadS3", "true"]
        }
    )
    print("Job submitted!")
    print("job name", resp["jobName"], "job ID", resp["jobId"])

submit_job() 関数について簡単に説明しよう. MNIST 手書き文字認識 (再訪) で, MNIST の Docker をローカルで実行したとき,次のようなコマンドを使用した.

sh
$ docker run -it mymnist --lr 0.1 --momentum 0.5 --epochs 10
$ docker run -it mymnist --lr 0.1 --momentum 0.5 --epochs 10

ここで, --lr 0.1 --momentum 0.5 --epochs 10 の部分が,コンテナに渡されるコマンドである.

AWS Batch でジョブを実行する際も,ContainerOverridescommand というパラメータを使用することで,コンテナに渡されるコマンドを指定することができる. コードでは以下の部分が該当する.

python
containerOverrides={
    "command": ["--lr", str(lr),
                "--momentum", str(momentum),
                "--epochs", str(epochs),
                "--uploadS3", "true"]
}
containerOverrides={
    "command": ["--lr", str(lr),
                "--momentum", str(momentum),
                "--epochs", str(epochs),
                "--uploadS3", "true"]
}

続いて, [4] 番のセルに移ろう. ここでは,上記の submit_job() 関数を用いて, 学習率 = 0.01, モメンタム=0.1, エポック数=100 を指定したジョブを投入する.

python
# [4]
submit_job(0.01, 0.1, 100)
# [4]
submit_job(0.01, 0.1, 100)

AWS の認証情報は, Jupyter Notebook の内部から再度定義する必要がある. これを手助けするため, Notebook の [2] 番のセル (デフォルトではすべてコメントアウトされている) を用意した. これを使うにはコメントアウトを解除すればよい. このセルを実行すると, AWS の認証情報を入力する対話的なプロンプトが表示される. プロンプトに従って aws secret key などを入力することで, (Jupyter のセッションに固有な) 環境変数に AWS の認証情報が記録される.

もう一つの認証方法として, submit_job() 関数に profile_name というパラメータを用意した. もし ~/.aws/credentials に認証情報が書き込まれているのならば (詳しくは (#aws_cli_install)), profile_name に使用したいプロファイルの名前を渡すだけで, 認証を行うことができる. 慣れている読者は後者のほうが便利であると感じるだろう.

[4] 番のセルを実行したら,ジョブが実際に投入されたかどうかを AWS コンソールから確認してみよう. AWS Batch の管理コンソールを開くと, figure_title のような画面が表示されるだろう.

AWS Batch でジョブが実行されている様子

figure_title で赤で囲った箇所に注目してほしい. 一つのジョブが投入されると,それは SUBMITTED という状態を経て RUNNABLE という状態に遷移する. RUNNABLE とは, ジョブを実行するためのインスタンスが Compute environment に不足しているため,新たなインスタンスが起動されるのを待っている状態に相当する. インスタンスの準備が整うと,ジョブの状態は STARTING を経て RUNNING に至る.

次に,ジョブのステータスが RUNNING のときの Compute environment の Desired vCPU を見てみよう (figure_title で紫で囲った箇所). ここで 4 と表示されているのは, g4dn.xlarge インスタンス一つ分の vCPU の数である. ジョブの投入に応じて,それを実行するのに最低限必要な EC2 インスタンスが起動されたことが確認できる (興味のある人は, EC2 コンソールも同時に覗いてみるとよい).

しばらく経つと,ジョブの状態は RUNNING から SUCCEEDED (あるいは何らかの理由でエラーが発生したときには FAILED) に遷移する. 今回のハンズオンで使っている MNIST の学習はだいたい 10 分くらいで完了するはずである. ジョブの状態が SUCCEEDED になるまで見届けよう.

ジョブが完了すると,学習の結果 (エポックごとの Loss と Accuracy を記録した CSV ファイル) は S3 に保存される. AWS コンソールからこれを確認しよう.

S3 のコンソールに行くと simplebatch-bucketXXXX (XXXX の部分はユーザーによって異なる) という名前のバケットが見つかるはずである. これをクリックして中身を見てみると, metrics_lr0.0100_m0.1000.csv という名前の CSV があることが確認できるだろう (figure_title). これが, 学習率 = 0.01, モメンタム = 0.1 として学習を行ったときの結果である.

ジョブの実行結果は S3 に保存される

さて,ここで run_single.ipynb に戻ってこよう. [5] から [7] 番のセルでは,学習結果の CSV ファイルのダウンロードを行っている.

python
# [5]
import pandas as pd
import io
from matplotlib import pyplot as plt

# [6]
def read_table_from_s3(bucket_name, key, profile_name=None):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    s3 = session.resource("s3")
    bucket = s3.Bucket(bucket_name)

    obj = bucket.Object(key).get().get("Body")
    df = pd.read_csv(obj)

    return df

# [7]
bucket_name = "simplebatch-bucket43879c71-mbqaltx441fu"
df = read_table_from_s3(
    bucket_name,
    "metrics_lr0.0100_m0.1000.csv"
)
# [5]
import pandas as pd
import io
from matplotlib import pyplot as plt

# [6]
def read_table_from_s3(bucket_name, key, profile_name=None):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    s3 = session.resource("s3")
    bucket = s3.Bucket(bucket_name)

    obj = bucket.Object(key).get().get("Body")
    df = pd.read_csv(obj)

    return df

# [7]
bucket_name = "simplebatch-bucket43879c71-mbqaltx441fu"
df = read_table_from_s3(
    bucket_name,
    "metrics_lr0.0100_m0.1000.csv"
)

[6] で S3 から CSV データをダウンロードし, pandas の DataFrame オブジェクトとしてロードする関数を定義している. [7] を実行する際, bucket_name という変数の値を,自分自身のバケットの名前に置き換えることに注意しよう (先ほど S3 コンソールから確認した simplebatch-bucketXXXX のことである).

続いて, [9] 番のセルで, CSV のデータをプロットしている (figure_title). ローカルで実行したときと同じように, AWS Batch を用いて MNIST モデルを訓練することに成功した!

python
# [9]
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(9,4))
x = [i for i in range(df.shape[0])]
ax1.plot(x, df["train_loss"], label="Train")
ax1.plot(x, df["val_loss"], label="Val")
ax2.plot(x, df["val_accuracy"])

ax1.set_xlabel("Epochs")
ax1.set_ylabel("Loss")
ax1.legend()

ax2.set_xlabel("Epochs")
ax2.set_ylabel("Accuracy")

print("Best loss:", df["val_loss"].min())
print("Best loss epoch:", df["val_loss"].argmin())
print("Best accuracy:", df["val_accuracy"].max())
print("Best accuracy epoch:", df["val_accuracy"].argmax())
# [9]
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(9,4))
x = [i for i in range(df.shape[0])]
ax1.plot(x, df["train_loss"], label="Train")
ax1.plot(x, df["val_loss"], label="Val")
ax2.plot(x, df["val_accuracy"])

ax1.set_xlabel("Epochs")
ax1.set_ylabel("Loss")
ax1.legend()

ax2.set_xlabel("Epochs")
ax2.set_ylabel("Accuracy")

print("Best loss:", df["val_loss"].min())
print("Best loss epoch:", df["val_loss"].argmin())
print("Best accuracy:", df["val_accuracy"].max())
print("Best accuracy epoch:", df["val_accuracy"].argmax())

AWS Batch で行った MNIST モデルの学習の結果

並列に複数の Job を実行する

さて,ここからが最後の仕上げである. ここまでのハンズオンで構築した AWS Batch のシステムを使って,ハイパーパラメータサーチを実際に行おう.

先ほど実行した run_single.ipynb と同じディレクトリにある run_sweep.ipynb を開く.

セル [1], [2], [3] は run_single.ipynb と同一である.

python
# [1]
import boto3
import argparse

# [2]
# AWS 認証ヘルパー ...省略...

# [3]
def submit_job(lr:float, momentum:float, epochs:int, profile_name=None):
    # ...省略...
# [1]
import boto3
import argparse

# [2]
# AWS 認証ヘルパー ...省略...

# [3]
def submit_job(lr:float, momentum:float, epochs:int, profile_name=None):
    # ...省略...

セル [4] の for ループを使って,グリッド状にハイパーパラメータの組み合わせを用意し, batch にジョブを投入している. ここでは 3x3=9 個のジョブを作成した.

python
# [4]
for lr in [0.1, 0.01, 0.001]:
    for m in [0.5, 0.1, 0.05]:
        submit_job(lr, m, 100)
# [4]
for lr in [0.1, 0.01, 0.001]:
    for m in [0.5, 0.1, 0.05]:
        submit_job(lr, m, 100)

セル [4] を実行したら, Batch のコンソールを開こう. 先ほどと同様に,ジョブのステータスは SUBMITTED > RUNNABLE > STARTING > RUNNING と移り変わっていくことがわかるだろう. 最終的に 9 個のジョブがすべて RUNNING の状態になることを確認しよう (figure_title). また,このとき Compute environment の Desired vCPUs は 4x9=36 となっていることを確認しよう (figure_title).

複数のジョブを同時投入したときの Batch コンソール

次に,Batch のコンソールの左側のメニューから Jobs をクリックしてみよう. ここでは,実行中のジョブの一覧が確認することができる (figure_title). ジョブのステータスでフィルタリングをすることも可能である. 9 個のジョブがどれも RUNNING 状態にあることが確認できるだろう.

複数のジョブを同時投入したときの Job 一覧

今度は EC2 コンソールを見てみよう. 左のメニューから Instances を選択すると, figure_title に示すような起動中のインスタンスの一覧が表示される. g4dn.xlarge が 9 台稼働しているのが確認できる. Batch がジョブの投下に合わせて必要な数のインスタンスを起動してくれたのだ!

複数のジョブを同時投入したときの EC2 インスタンスの一覧

ここまで確認できたら,それぞれの Job が終了するまでしばらく待とう (だいたい 10-15 分くらいで終わる). すべてのジョブが終了すると,ダッシュボードの SUCCEEDED が 9 となっているはずだ. また, Compute environment の Desired vCPUs も 0 に落ちていることを確認しよう. 最後に EC2 コンソールに行って,すべての g4dn インスタンスが停止していることを確認しよう.

以上から, AWS Batch を使うことで,ジョブの投入に応じて自動的に EC2 インスタンスが起動され,ジョブの完了とともに,ただちにインスタンスの停止が行われる一連の挙動を観察することができた. 一つのジョブの完了におよそ 10 分の時間がかかるので,9 個のハイパーパラメータの組を逐次的に計算していた場合は 90 分の時間を要することになる. AWS Batch を使ってこれらの計算を並列に実行することで,ジョブ一個分の計算時間 (=10 分) ですべての計算を終えることができた!

さて,再び run_sweep.ipynb に戻ってこよう. [5] 以降のセルでは,グリッドサーチの結果を可視化している.

python
# [5]
import pandas as pd
import numpy as np
import io
from matplotlib import pyplot as plt

# [6]
def read_table_from_s3(bucket_name, key, profile_name=None):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    s3 = session.resource("s3")
    bucket = s3.Bucket(bucket_name)

    obj = bucket.Object(key).get().get("Body")
    df = pd.read_csv(obj)

    return df

# [7]
grid = np.zeros((3,3))
for (i, lr) in enumerate([0.1, 0.01, 0.001]):
    for (j, m) in enumerate([0.5, 0.1, 0.05]):
        key = f"metrics_lr{lr:0.4f}_m{m:0.4f}.csv"
        df = read_table_from_s3("simplebatch-bucket43879c71-mbqaltx441fu", key)
        grid[i,j] = df["val_accuracy"].max()

# [8]
fig, ax = plt.subplots(figsize=(6,6))
ax.set_aspect('equal')

c = ax.pcolor(grid, edgecolors='w', linewidths=2)

for i in range(3):
    for j in range(3):
        text = ax.text(j+0.5, i+0.5, f"{grid[i, j]:0.1f}",
                       ha="center", va="center", color="w")
# [5]
import pandas as pd
import numpy as np
import io
from matplotlib import pyplot as plt

# [6]
def read_table_from_s3(bucket_name, key, profile_name=None):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    s3 = session.resource("s3")
    bucket = s3.Bucket(bucket_name)

    obj = bucket.Object(key).get().get("Body")
    df = pd.read_csv(obj)

    return df

# [7]
grid = np.zeros((3,3))
for (i, lr) in enumerate([0.1, 0.01, 0.001]):
    for (j, m) in enumerate([0.5, 0.1, 0.05]):
        key = f"metrics_lr{lr:0.4f}_m{m:0.4f}.csv"
        df = read_table_from_s3("simplebatch-bucket43879c71-mbqaltx441fu", key)
        grid[i,j] = df["val_accuracy"].max()

# [8]
fig, ax = plt.subplots(figsize=(6,6))
ax.set_aspect('equal')

c = ax.pcolor(grid, edgecolors='w', linewidths=2)

for i in range(3):
    for j in range(3):
        text = ax.text(j+0.5, i+0.5, f"{grid[i, j]:0.1f}",
                       ha="center", va="center", color="w")

最終的に出力されるプロットが figure_title である.

ハイパーパラメータのグリッドサーチの結果

このプロットから,差は僅かであるが,学習率が 0.1 のときに精度は最大となることがわかる. また,学習率 0.1 のときはモメンタムを変えても大きな差は生じないことが見て取れる.

今回のパラメータサーチは勉強用に極めて単純化されたものである点は承知いただきたい.

たとえば,今回は学習率が 0.1 が最も良いとされたが,それは訓練のエポックを 100 に限定しているからかもしれない. 学習率が低いとその分訓練に必要なエポック数も多くなる. 訓練のエポック数をもっと増やせばまた違った結果が観察される可能性はある.

また,今回は MNIST の訓練データ 60,000 枚のうち, 48,000 枚を訓練データ,残り 12,000 枚を検証データとして用いた. この分割は乱数を固定してランダムに行ったが,もしこの分割によるデータのバイアスを気にするならば, k 個の異なる学習・検証データの分割をあらかじめ用意して,複数回モデルの評価を行う (k-fold cross-validation) 方法も,より精緻なアプローチとして考えられる.

以上のようにして, CNN を用いた MNIST 分類モデルのハイパーパラメータの最適化の一連の流れを体験した. AWS Batch を利用することで,比較的少ないプログラミングで,動的に EC2 クラスターを制御し,並列にジョブを処理するシステムが構築できた. ここまで EC2 を使いこなすことができれば,多くの問題を自力で解くことが可能になるだろう!

スタックの削除

これにて,本ハンズオンは終了である.最後にスタックを削除しよう. 今回のスタックを削除するにあたり,ECR に配置された Docker のイメージは手動で削除されなければならない (これをしないと, cdk destroy を実行したときにエラーになってしまう. これは CloudFormation の仕様なので従うしかない).

ECR の Docker image を削除するには, ECR のコンソールに行き,イメージが配置されたレポジトリを開く. そして,画面右上の DELETE ボタンを押して削除する (figure_title).

ECR から Docker image を削除する

あるいは, AWS CLI から同様の操作を行うには,以下のコマンドを用いる (XXXX は自分の ECR レポジトリ名に置き換える).

sh
$ aws ecr batch-delete-image --repository-name XXXX --image-ids imageTag=latest
$ aws ecr batch-delete-image --repository-name XXXX --image-ids imageTag=latest

image の削除が完了したうえで,次のコマンドでスタックを削除する.

sh
$ cdk destroy
$ cdk destroy

(#sec:batch_development_and_debug) === クラウドを用いた機械学習アプリケーションの開発とデバッグ

本章で紹介したハンズオンでは, AWS Batch を使用することでニューラルネットの学習を複数並列に実行し,高速化を実現した. 本章の最後の話題として,クラウドを用いた機械学習アプリケーションの開発とデバッグの方法について述べよう.

ローカルに GPU を搭載した強力なマシンがなく,クラウドを利用する予算が確保されているのであれば, figure_title のような開発のスキームが理想的であると考える. 最初の段階では, (#sec_jupyter_and_deep_learning) で見たような方法で, GPU 搭載型の EC2 インスタンスを作成し, Jupyter Notebook などのインタラクティブな環境で様々なモデルを試し実験を行う. Jupyter である程度アプリケーションが完成してきたタイミングで,作成したアプリケーションを Docker イメージにパッケージングする. そして, EC2 上で docker run を行い,作成したイメージがバグなく動作するか確認を行う. その次に,ハイパーパラメータの最適化などのチューニングを, Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する のハンズオンで学んだ AWS Batch などの計算システムを利用して行う. よい深層学習モデルが完成したら,仕上げに大規模データへの推論処理を行うシステムを (#sec_fargate_qabot) を参考に構築する.

実際,本書ではこの流れに沿って演習を進めてきた. MNIST タスクを解くモデルを,最初 Jupyter Notebook を使用して実験し,そのコードをほとんどそのまま Docker にパッケージし, AWS Batch を用いてハイパーパラメータサーチを行った. このサイクルを繰り返すことで,クラウドを最大限に活用した機械学習アプリケーションの開発を進めることができる.

クラウドを活用した機械学習アプリケーションの開発フロー

小括

ここまでが,本書第二部の内容である. 第一部に引き続き盛りだくさんの内容であったが,ついてこれたであろうか?

第二部ではまず最初に,深層学習の計算をクラウドで実行するため, GPU 搭載型の EC2 インスタンスの起動について解説した. さらに,ハンズオンでは,クラウドに起動した仮想サーバーを使って MNIST 文字認識タスクを解くニューラルネットを訓練した ( (#sec_jupyter_and_deep_learning)).

また,より大規模な機械学習アプリケーションを作るための手段として, Docker と ECS によるクラスターの初歩を説明した ( (#sec_docker_introduction)). その応用として,英語で与えられた文章問題への回答を自動で生成するボットをクラウドに展開した ( (#sec_fargate_qabot)). タスクの投入に応じて動的に計算リソースが作成・削除される様子を実際に体験できただろう.

さらに, Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する では AWS Batch を用いてニューラルネットの学習を並列に実行する方法を紹介した. ここで紹介した方法は,ミニマムであるが,計算機システムを大規模化していくためのエッセンスが網羅されている. これらのハンズオン体験から,クラウド技術を応用してどのように現実世界の問題を解いていくのか,なんとなくイメージが伝わっただろうか?

本書の第三部では,さらにレベルアップし,サーバーレスアーキテクチャという最新のクラウドの設計手法について解説する. その応用として,ハンズオンでは簡単な SNS サービスをゼロから実装する. 引き続きクラウドの最先端の世界を楽しんでいこう!

]]>
<![CDATA[AWS 入門 ]]> https://note.toshiki.dev/development/aws/aws-get-started https://note.toshiki.dev/development/aws/aws-get-started Thu, 01 Jul 2021 00:00:00 GMT AWS 入門

AWS とは?

本書では,クラウドの実践を行うプラットフォームとして, AWS を用いる. 実践にあたって,最低限必要な AWS の知識を本章では解説しよう.

AWS (Amazon Web Services) は Amazon 社が提供する総合的なクラウドプラットフォームである. AWS は Amazon 社が持つ膨大な計算リソースを貸し出すクラウドサービスとして,2006 年に誕生した. 2021 年では,クラウドプロバイダーとして最大のマーケットシェア (約 32%) を保持している (参照). Netflix や Slack をはじめとした多くのウェブ関連のサービスで,一部または全てのサーバーリソースが AWS から提供されているとのことである. よって,知らないうちに AWS の恩恵にあずかっている人も少なくないはずだ.

最大のシェアをもつだけに,機能・サービスの幅広さはほかのクラウドプラットフォームと比べ抜きんでている. また,利用者数が多いことを反映して,公式あるいはサードパーティによる技術紹介記事が数多くウェブ上に存在しているだけでなく,ライブラリのユーザーコミュニティも大きく問題解決が捗るのも魅力の一つだ. 初期のころウェブビジネスを行う企業がユーザーの大半を占めていたが,最近は大学などでの科学研究用途としても頻繁に用いられるようになってきている.

AWS の機能・サービス

figure_title は,執筆時点において AWS で提供されている主要な機能・サービスの一覧である.

AWSで提供されている主要なサービス一覧

計算,ストレージ,データベース,ネットワーク,セキュリティなど,クラウドの構築に必要な様々な要素が独立したコンポーネントとして提供されている. 基本的に,これらを組み合わせることで一つのクラウドシステムができあがる.

また,機械学習・音声認識・AR/VR など,特定のアプリケーションにパッケージ済みのサービスも提供されている. これらを合計すると全部で 170 個以上のサービスが提供されているとのことである (参照).

AWS の初心者が陥りがちなのは,大量のサービスの数に圧倒され,どこから手をつけたらよいのかわからなくなる,という状況である. たくさんのサービスの中から,どのサービスをどの順番で学んでいったらいいのか,その道筋すら明らかでなく,大きな参入障壁となっていることは間違いない. だが実のところ, AWS の基本的な構成要素はそのうちの数個のみに限られる. 基本要素となる機能の使い方を知れば, AWS のおおよそのリソースを使いこなすことが可能になる. ほかの機能の多くは,基本の要素を組み合わせて特定のアプリケーションに特化したパッケージとして AWS が用意したものである. そのポイントを認知することが, AWS の学習の最初のステップである.

ここでは, AWS 上でクラウドシステムを構築するときの基本となる構成要素を列挙する. これらは後のハンズオンで実際にプログラムを書きながら体験する. 現時点では,名前だけでも頭の片隅に記憶してもらえればよい.

計算

S3 EC2 (Elastic Compute Cloud) 様々なスペックの仮想マシンを作成し,計算を実行することができる. クラウドの最も基本となる構成要素である. (#sec_first_ec2), (#sec_jupyter_and_deep_learning), (#sec_aws_batch) で詳しく触れる.

S3 Lambda Function as a Service (FaaS) とよばれる,小さな計算をサーバーなしで実行するためのサービス. サーバーレスアーキテクチャの章 ( (#sec_serverless)) で詳しく解説する.

ストレージ

S3 EBS (Elastic Block Store) EC2 に付与することのできる仮想データドライブ. いわゆる"普通の"(一般的な OS で使われている)ファイルシステムを思い浮かべてくれたらよい.

S3

S3 (Simple Storage Service) Object Storage とよばれる,API を使ってデータの読み書きを行う,いうなれば”クラウド・ネイティブ”なデータの格納システムである. サーバーレスアーキテクチャの章 ( (#sec_serverless)) で詳しく解説する.

データベース

S3

DynamoDB NoSQL 型のデータベースサービス (知っている人は mongoDB などを思い浮かべたらよい). サーバーレスアーキテクチャの章 ( (#sec_serverless)) で詳しく解説する.

ネットワーク

S3 VPC(Virtual Private Cloud) AWS 上に仮想ネットワーク環境を作成し,仮想サーバー間の接続を定義したり,外部からのアクセスなどを管理する. EC2 は VPC の内部に配置されなければならない.

API Gateway S3

API のエンドポイントとバックエンドのサービス (Lambda など) を接続する際に用いる,リバースプロキシとしての役割を担う. (#sec_bashoutter) で詳しく解説する.

Region と Availability Zone

AWS を使用する際に知っておかなければならない重要な概念として, リージョン (Region)Availability Zone (AZ) がある (figure_title). 以下ではこの概念について簡単に記述する.

AWSにおける Region と Availability Zones

リージョン (Region) とは,おおまかに言うとデータセンターの所在地のことである. 執筆時点において, AWS は世界の 25 の国と地域でデータセンターを所有している. figure_title は執筆時点で利用できるリージョンの世界地図を示している. 日本では東京と大阪にデータセンターがある. 各リージョンには固有の ID がついており,例えば東京は ap-northeast-1, 米国オハイオ州は us-east-2,などと定義されている.

Regions in AWS(出典: https://aws.amazon.com/about-aws/global-infrastructure/)

AWS コンソールにログインすると,画面右上のメニューバーでリージョンを選択することができる(figure_title, 赤丸で囲った箇所). EC2, S3 などの AWS のリソースは,リージョンごとに完全に独立である. したがって,リソースを新たにデプロイする際,あるいはデプロイ済みのリソースを閲覧する際は,コンソールのリージョンが正しく設定されているか,確認する必要がある. ウェブビジネスを展開する場合などは,世界の各地にクラウドを展開する必要があるが,個人的な研究用途として用いる場合は,最寄りのリージョン (i.e. 東京) を使えば基本的に問題ない.

AWSコンソールでリージョンを選択

Avaialibity Zone (AZ) とは,リージョン内で地理的に隔離されたデータセンターのことである. それぞれのリージョンは 2 個以上の AZ を有しており,もし一つの AZ で火災や停電などが起きた場合でも,ほかの AZ がその障害をカバーすることができる. また, AZ 間は高速な AWS 専用ネットワーク回線で結ばれているため, AZ 間のデータ転送は極めて早い. AZ は,ビジネスなどでサーバーダウンが許容されない場合などに注意すべき概念であり,個人的な用途で使う限りにおいてはあまり深く考慮する必要はない.言葉の意味だけ知っておけば十分である.

AWS を使用する際,どこのリージョンを指定するのがよいのだろうか? インターネットの接続速度の観点からは,地理的に一番近いリージョンを使用するのが一般的によいだろう. 一方, EC2 の利用料などはリージョンごとに価格設定が若干 (10-20%程度) 異なる. したがって,自分が最も頻繁に利用するサービスの価格が最も安く設定されているリージョンを選択する,というのも重要な視点である. また,いくつかのサービスは,特定のリージョンで利用できない場合もある. これらのポイントから総合的に判断して使用するリージョンを決めると良い.

AWS Educate を利用している読者へ

執筆時点において,AWS Educate による Starter Account を使用している場合は us-east-1 region のみ利用できる (参照).

AWS でのクラウド開発

AWS のクラウドの全体像がわかってきたところで,次のトピックとして,どのようにして AWS 上にクラウドの開発を行い,展開していくかについての概略を解説しよう.

AWS のリソースを追加・編集・削除するなどの操作を実行するには,コンソールを用いる方法と,API を用いる方法の,二つの経路がある.

コンソール画面からリソースを操作する

AWS のアカウントにログインすると,まず最初に表示されるのがAWS コンソールである (figure_title).

AWSマネージメントコンソール画面

コンソールを使うことで, EC2 のインスタンスを立ち上げたり,S3 のデータを追加・削除したり,ログを閲覧したりなど,AWS 上のあらゆるリソースの操作を GUI (Graphical User Interface) を通して実行することができる. 初めて触る機能をポチポチと試したり,デバッグを行うときなどにとても便利である

コンソールはさらっと機能を試したり,開発中のクラウドのデバッグをするときには便利なのであるが,実際にクラウドの開発をする場面でこれを直接いじることはあまりない. むしろ,次に紹介する API を使用して,プログラムとしてクラウドのリソースを記述することで開発を行うのが一般的である. そのような理由で,本書では AWS コンソールを使った AWS の使い方はあまり触れない. AWS のドキュメンテーションには,たくさんの チュートリアル が用意されており,コンソール画面から様々な操作を行う方法が記述されているので,興味がある読者はそちらを参照されたい.

API からリソースを操作する

API (Application Programming Interface) を使うことで,コマンドを AWS に送信し,クラウドのリソースの操作をすることができる. API とは,端的に言えば AWS が公開しているコマンドの一覧であり,GET, POST, DELETE などの REST API から構成されている (REST API については (#sec_rest_api) で簡単に解説する). が,直接 REST API を入力するのは面倒であるので,その手間を解消するための様々なツールが提供されている.

例えば, AWS CLI は, UNIX コンソールから AWS API を実行するための CLI (Command Line Interface) である. CLI に加えて,いろいろなプログラミング言語での SDK (Software Development Kit) が提供されている.以下に一例を挙げる.

具体的な API の使用例を見てみよう.

S3 に新しい保存領域 (Bucket (バケット) とよばれる) を追加したいとしよう. AWS CLI を使った場合は,次のようなコマンドを打てばよい.

sh
$ aws s3 mb s3://my-bucket --region ap-northeast-1
$ aws s3 mb s3://my-bucket --region ap-northeast-1

上記のコマンドは, my-bucket という名前のバケットを, ap-northeast-1 のリージョンに作成する.

Python からこれと同じ操作を実行するには, boto3 ライブラリを使って,次のようなスクリプトを実行する.

python
import boto3

s3_client = boto3.client("s3", region_name="ap-northeast-1")
s3_client.create_bucket(Bucket="my-bucket")
import boto3

s3_client = boto3.client("s3", region_name="ap-northeast-1")
s3_client.create_bucket(Bucket="my-bucket")

もう一つ例をあげよう.

新しい EC2 のインスタンス(インスタンスとは,起動状態にある仮想サーバーの意味である)を起動するには,次のようなコマンドを打てば良い.

sh
$ aws ec2 run-instances --image-id ami-xxxxxxxx --count 1 --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-903004f8 --subnet-id subnet-6e7f829e
$ aws ec2 run-instances --image-id ami-xxxxxxxx --count 1 --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-903004f8 --subnet-id subnet-6e7f829e

このコマンドにより, t2.micro というタイプ (1 vCPU, 1.0 GB RAM) のインスタンスが起動する. ここではその他のパラメータの詳細の説明は省略する (ハンズオン ( (#sec_first_ec2)) で詳しく解説する).

Python から上記と同じ操作を実行するには,以下のようなスクリプトを使う.

python
import boto3

ec2_client = boto3.client("ec2")
ec2_client.run_instances(
    ImageId="ami-xxxxxxxxx",
    MinCount=1,
    MaxCount=1,
    KeyName="MyKeyPair",
    InstanceType="t2.micro",
    SecurityGroupIds=["sg-903004f8"],
    SubnetId="subnet-6e7f829e",
)
import boto3

ec2_client = boto3.client("ec2")
ec2_client.run_instances(
    ImageId="ami-xxxxxxxxx",
    MinCount=1,
    MaxCount=1,
    KeyName="MyKeyPair",
    InstanceType="t2.micro",
    SecurityGroupIds=["sg-903004f8"],
    SubnetId="subnet-6e7f829e",
)

以上の例を通じて,API によるクラウドのリソースの操作のイメージがつかめてきただろうか? コマンド一つで,新しい仮想サーバーを起動したり,データの保存領域を追加したり,任意の操作を実行できるわけである. 基本的に,このようなコマンドを複数組み合わせていくことで,自分の望む CPU・RAM・ネットワーク・ストレージが備わった計算環境を構築することができる. もちろん,逆の操作 (リソースの削除) も API を使って実行できる.

ミニ・ハンズオン: AWS CLI を使ってみよう

ここでは,ミニ・ハンズオンとして,AWS CLI を実際に使ってみる. AWS CLI は先述のとおり, AWS 上の任意のリソースの操作が可能であるが,ここでは一番シンプルな,S3 を使ったファイルの読み書きを実践する (EC2 の操作は少し複雑なので,第一回ハンズオンで行う). aws s3 コマンドの詳しい使い方は 公式ドキュメンテーションを参照.

AWS CLI のインストールについては, (#aws_cli_install) を参照.

以下に紹介するハンズオンは,基本的に S3 の無料枠 の範囲内で実行することができる.

以下のコマンドを実行する前に,AWS の認証情報が正しく設定されていることを確認する. これには ~/.aws/credentials のファイルに設定が書き込まれているか,環境変数 (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION) が定義されている必要がある. 詳しくは (#aws_cli_install) を参照.

まずは,S3 にデータの格納領域 (Bucket とよばれる.一般的な OS での"ドライブ"に相当する) を作成するところから始めよう.

sh
$ bucketName="mybucket-$(openssl rand -hex 12)"
$ echo $bucketName
$ aws s3 mb "s3://${bucketName}"
$ bucketName="mybucket-$(openssl rand -hex 12)"
$ echo $bucketName
$ aws s3 mb "s3://${bucketName}"

S3 のバケットの名前は, AWS 全体で一意的でなければならないことから,前述のコマンドではランダムな文字列を含んだバケットの名前を生成し,bucketName という変数に格納している. そして, aws s3 mb (mb は make bucket の略) によって,新しいバケットを作成する.

次に,バケットの一覧を取得してみよう.

sh
$ aws s3 ls

2020-06-07 23:45:44 mybucket-c6f93855550a72b5b66f5efe
$ aws s3 ls

2020-06-07 23:45:44 mybucket-c6f93855550a72b5b66f5efe

先ほど作成したバケットがリストにあることを確認できる.

本書のノーテーションとして,コマンドラインに入力するコマンドは,それがコマンドであると明示する目的で先頭に $ がつけてある. $ はコマンドをコピー&ペーストするときは除かなければならない. 逆に,コマンドの出力は $ なしで表示されている.

次に,バケットにファイルをアップロードする.

sh
$ echo "Hello world" > hello_world.txt
$ aws s3 cp hello_world.txt "s3://${bucketName}/hello_world.txt"
$ echo "Hello world" > hello_world.txt
$ aws s3 cp hello_world.txt "s3://${bucketName}/hello_world.txt"

上では hello_world.txt というダミーのファイルを作成して,それをアップロードした.

それでは,バケットの中にあるファイルの一覧を取得してみる.

sh
$ aws s3 ls "s3://${bucketName}" --human-readable

2020-06-07 23:54:19   13 Bytes hello_world.txt
$ aws s3 ls "s3://${bucketName}" --human-readable

2020-06-07 23:54:19   13 Bytes hello_world.txt

先ほどアップロードしたファイルがたしかに存在することがわかる.

最後に,使い終わったバケットを削除する.

sh
$ aws s3 rb "s3://${bucketName}" --force
$ aws s3 rb "s3://${bucketName}" --force

rb は remove bucket の略である. デフォルトでは,バケットの中にファイルが存在すると削除できない. 空でないバケットを強制的に削除するには --force のオプションを付ける.

以上のように,AWS CLI を使って S3 バケットに対しての一連の操作を実行できた. EC2 や Lambda, DynamoDB などについても同様に AWS CLI を使ってあらゆる操作を実行できる.

Amazon Resource Name (ARN)

AWS 上のあらゆるリソースには, Amazon Resource Name (ARN) という固有の ID が付与されている. ARN は arn:aws:s3:::my_bucket/ のようなフォーマットで記述され,ARN を使用することで,特定の AWS リソース (S3 のバケットや EC2 のインスタンス) を一意的に参照することができる.

S3 バケットや EC2 インスタンスなどには ARN に加えて,人間が読みやすい名前を定義することも可能である. この場合は,ARN または名前のどちらを用いても同じリソースを参照することが可能である.

CloudFormation と AWS CDK

CloudFormation による Infrastructure as Code (IaC)

前節で述べたように,AWS API を使うことでクラウドのあらゆるリソースの作成・管理が可能である. よって,原理上は, API のコマンドを組み合わせていくことで,自分の作りたいクラウドを設計することができる.

しかし,ここで実用上考慮しなければならない点が一つある. AWS API には大きく分けて,リソースを操作するコマンドと,タスクを実行するコマンドがあることである (figure_title).

AWS APIはリソースを操作するコマンドとタスクを実行するコマンドに大きく分けられる.リソースを記述・管理するのに使われるのが, CloudFormation と CDK である.

リソースを操作するとは,EC2 のインスタンスを起動したり,S3 のバケットを作成したり,データベースに新たなテーブルを追加する,などの静的なリソースを準備する 操作を指す. "ハコ"を作る操作とよんでも良いだろう. このようなコマンドは,クラウドのデプロイ時にのみ,一度だけ実行されればよい

タスクを実行するコマンド とは, EC2 のインスタンスにジョブを投入したり, S3 のバケットにデータを読み書きするなどの操作を指す. これは, EC2 や S3 などのリソース ("ハコ") を前提として,その内部で実行されるべき計算を記述するものである. 前者に比べてこちらは動的な操作を担当する,と捉えることもできる.

そのような観点から,インフラを記述するプログラムタスクを実行するプログラムはある程度分けて管理されるべきである. クラウドの開発は,クラウドの(静的な)リソースを記述するプログラムを作成するステップと,インフラ上で動く動的な操作を行うプログラムを作成するステップの二段階に分けて考えることができる.

AWS での静的リソースを管理するための仕組みが, CloudFormation である. CloudFormation とは, CloudFormation の文法に従ったテキストファイルを使って,AWS のインフラを記述する仕組みである. CloudFormation を使って,たとえば,EC2 のインスタンスをどれくらいのスペックで,何個起動するか,インスタンス間はどのようなネットワークで結び,どのようなアクセス権限を付与するか,などのリソースの要件を逐次的に記述することができる. 一度 CloudFormation ファイルができ上がれば,それにしたがったクラウドシステムをコマンド一つで AWS 上に展開することができる. また,CloudFormation ファイルを交換することで,全く同一のクラウド環境を他者が簡単に再現することも可能になる. このように,本来は物理的な実体のあるハードウェアを,プログラムによって記述し,管理するという考え方を,**Infrastructure as Code (IaC)**とよぶ.

CloudFormation を記述するには,基本的に JSON (JavaScript Object Notation) とよばれるフォーマットを使う. 次のコードは,JSON で記述された CloudFormation ファイルの一例 (抜粋) である.

json
"Resources" : {
  ...
  "WebServer": {
    "Type" : "AWS::EC2::Instance",
    "Properties": {
      "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" },
                        { "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" }, "Arch" ] } ] },
      "InstanceType"   : { "Ref" : "InstanceType" },
      "SecurityGroups" : [ {"Ref" : "WebServerSecurityGroup"} ],
      "KeyName"        : { "Ref" : "KeyName" },
      "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [
                     "#!/bin/bash -xe\n",
                     "yum update -y aws-cfn-bootstrap\n",

                     "/opt/aws/bin/cfn-init -v ",
                     "         --stack ", { "Ref" : "AWS::StackName" },
                     "         --resource WebServer ",
                     "         --configsets wordpress_install ",
                     "         --region ", { "Ref" : "AWS::Region" }, "\n",

                     "/opt/aws/bin/cfn-signal -e $? ",
                     "         --stack ", { "Ref" : "AWS::StackName" },
                     "         --resource WebServer ",
                     "         --region ", { "Ref" : "AWS::Region" }, "\n"
      ]]}}
    },
    ...
  },
  ...
},
"Resources" : {
  ...
  "WebServer": {
    "Type" : "AWS::EC2::Instance",
    "Properties": {
      "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" },
                        { "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" }, "Arch" ] } ] },
      "InstanceType"   : { "Ref" : "InstanceType" },
      "SecurityGroups" : [ {"Ref" : "WebServerSecurityGroup"} ],
      "KeyName"        : { "Ref" : "KeyName" },
      "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [
                     "#!/bin/bash -xe\n",
                     "yum update -y aws-cfn-bootstrap\n",

                     "/opt/aws/bin/cfn-init -v ",
                     "         --stack ", { "Ref" : "AWS::StackName" },
                     "         --resource WebServer ",
                     "         --configsets wordpress_install ",
                     "         --region ", { "Ref" : "AWS::Region" }, "\n",

                     "/opt/aws/bin/cfn-signal -e $? ",
                     "         --stack ", { "Ref" : "AWS::StackName" },
                     "         --resource WebServer ",
                     "         --region ", { "Ref" : "AWS::Region" }, "\n"
      ]]}}
    },
    ...
  },
  ...
},

ここでは, "WebServer" という名前のつけられた EC2 インスタンスを定義している.かなり長大で複雑な記述であるが,これによって所望のスペック・OS をもつ EC2 インスタンスを自動的に生成することが可能になる.

AWS CDK

前節で紹介した CloudFormation は,見てわかるとおり大変記述が複雑であり,またそれのどれか一つにでも誤りがあってはいけない. また,基本的に"テキスト"を書いていくことになるので,プログラミング言語で使うような変数やクラスといった便利な概念が使えない (厳密には, CloudFormation にも変数に相当するような機能は存在する). また,記述の多くの部分は繰り返しが多く,自動化できる部分も多い.

そのような悩みを解決してくれるのが, AWS Cloud Development Kit (CDK) である. CDK は Python などのプログラミング言語を使って CloudFormation を自動的に生成してくれるツールである. CDK は 2019 年にリリースされたばかりの比較的新しいツールで,日々改良が進められている (GitHub リポジトリ のリリースを見ればその開発のスピードの速さがわかるだろう). CDK は TypeScript (JavaScript), Python, Java など複数の言語でサポートされている.

CDK を使うことで,CloudFormation に相当するクラウドリソースの記述を,より親しみのあるプログラミング言語を使って行うことができる. かつ,典型的なリソース操作に関してはパラメータの多くの部分を自動で決定してくれるので,記述しなければならない量もかなり削減される.

以下に Python を使った CDK のコードの一例 (抜粋) を示す.

python
from aws_cdk import (
    core,
    aws_ec2 as ec2,
)

class MyFirstEc2(core.Stack):

    def __init__(self, scope, name, **kwargs):
        super().__init__(scope, name, **kwargs)

        vpc = ec2.Vpc(
            ... # some parameters
        )

        sg = ec2.SecurityGroup(
            ... # some parameters
        )

        host = ec2.Instance(
            self, "MyGreatEc2",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ec2.MachineImage.latest_amazon_linux(),
            vpc=vpc,
            ...
        )
from aws_cdk import (
    core,
    aws_ec2 as ec2,
)

class MyFirstEc2(core.Stack):

    def __init__(self, scope, name, **kwargs):
        super().__init__(scope, name, **kwargs)

        vpc = ec2.Vpc(
            ... # some parameters
        )

        sg = ec2.SecurityGroup(
            ... # some parameters
        )

        host = ec2.Instance(
            self, "MyGreatEc2",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ec2.MachineImage.latest_amazon_linux(),
            vpc=vpc,
            ...
        )

このコードは,一つ前に示した JSON を使った CloudFormation と実質的に同じことを記述している. とても煩雑だった CloudFormation ファイルに比べて, CDK と Python を使うことで格段に短く,わかりやすく記述できることができるのがわかるだろう.

本書の主題は,CDK を使って,コードを書きながら AWS の概念や開発方法を学んでいくことである. 後の章では CDK を使って様々なハンズオンを実施していく. 早速,最初のハンズオンでは, CDK を使って EC2 インスタンスを作成する方法を学んでいこう.

  • AWS CDK Examples: CDK を使ったプロジェクトの例が多数紹介されている. ここにある例をテンプレートに自分のアプリケーションの開発を進めるとよい.
]]>
AWS 入門

AWS とは?

本書では,クラウドの実践を行うプラットフォームとして, AWS を用いる. 実践にあたって,最低限必要な AWS の知識を本章では解説しよう.

AWS (Amazon Web Services) は Amazon 社が提供する総合的なクラウドプラットフォームである. AWS は Amazon 社が持つ膨大な計算リソースを貸し出すクラウドサービスとして,2006 年に誕生した. 2021 年では,クラウドプロバイダーとして最大のマーケットシェア (約 32%) を保持している (参照). Netflix や Slack をはじめとした多くのウェブ関連のサービスで,一部または全てのサーバーリソースが AWS から提供されているとのことである. よって,知らないうちに AWS の恩恵にあずかっている人も少なくないはずだ.

最大のシェアをもつだけに,機能・サービスの幅広さはほかのクラウドプラットフォームと比べ抜きんでている. また,利用者数が多いことを反映して,公式あるいはサードパーティによる技術紹介記事が数多くウェブ上に存在しているだけでなく,ライブラリのユーザーコミュニティも大きく問題解決が捗るのも魅力の一つだ. 初期のころウェブビジネスを行う企業がユーザーの大半を占めていたが,最近は大学などでの科学研究用途としても頻繁に用いられるようになってきている.

AWS の機能・サービス

figure_title は,執筆時点において AWS で提供されている主要な機能・サービスの一覧である.

AWSで提供されている主要なサービス一覧

計算,ストレージ,データベース,ネットワーク,セキュリティなど,クラウドの構築に必要な様々な要素が独立したコンポーネントとして提供されている. 基本的に,これらを組み合わせることで一つのクラウドシステムができあがる.

また,機械学習・音声認識・AR/VR など,特定のアプリケーションにパッケージ済みのサービスも提供されている. これらを合計すると全部で 170 個以上のサービスが提供されているとのことである (参照).

AWS の初心者が陥りがちなのは,大量のサービスの数に圧倒され,どこから手をつけたらよいのかわからなくなる,という状況である. たくさんのサービスの中から,どのサービスをどの順番で学んでいったらいいのか,その道筋すら明らかでなく,大きな参入障壁となっていることは間違いない. だが実のところ, AWS の基本的な構成要素はそのうちの数個のみに限られる. 基本要素となる機能の使い方を知れば, AWS のおおよそのリソースを使いこなすことが可能になる. ほかの機能の多くは,基本の要素を組み合わせて特定のアプリケーションに特化したパッケージとして AWS が用意したものである. そのポイントを認知することが, AWS の学習の最初のステップである.

ここでは, AWS 上でクラウドシステムを構築するときの基本となる構成要素を列挙する. これらは後のハンズオンで実際にプログラムを書きながら体験する. 現時点では,名前だけでも頭の片隅に記憶してもらえればよい.

計算

S3 EC2 (Elastic Compute Cloud) 様々なスペックの仮想マシンを作成し,計算を実行することができる. クラウドの最も基本となる構成要素である. (#sec_first_ec2), (#sec_jupyter_and_deep_learning), (#sec_aws_batch) で詳しく触れる.

S3 Lambda Function as a Service (FaaS) とよばれる,小さな計算をサーバーなしで実行するためのサービス. サーバーレスアーキテクチャの章 ( (#sec_serverless)) で詳しく解説する.

ストレージ

S3 EBS (Elastic Block Store) EC2 に付与することのできる仮想データドライブ. いわゆる"普通の"(一般的な OS で使われている)ファイルシステムを思い浮かべてくれたらよい.

S3

S3 (Simple Storage Service) Object Storage とよばれる,API を使ってデータの読み書きを行う,いうなれば”クラウド・ネイティブ”なデータの格納システムである. サーバーレスアーキテクチャの章 ( (#sec_serverless)) で詳しく解説する.

データベース

S3

DynamoDB NoSQL 型のデータベースサービス (知っている人は mongoDB などを思い浮かべたらよい). サーバーレスアーキテクチャの章 ( (#sec_serverless)) で詳しく解説する.

ネットワーク

S3 VPC(Virtual Private Cloud) AWS 上に仮想ネットワーク環境を作成し,仮想サーバー間の接続を定義したり,外部からのアクセスなどを管理する. EC2 は VPC の内部に配置されなければならない.

API Gateway S3

API のエンドポイントとバックエンドのサービス (Lambda など) を接続する際に用いる,リバースプロキシとしての役割を担う. (#sec_bashoutter) で詳しく解説する.

Region と Availability Zone

AWS を使用する際に知っておかなければならない重要な概念として, リージョン (Region)Availability Zone (AZ) がある (figure_title). 以下ではこの概念について簡単に記述する.

AWSにおける Region と Availability Zones

リージョン (Region) とは,おおまかに言うとデータセンターの所在地のことである. 執筆時点において, AWS は世界の 25 の国と地域でデータセンターを所有している. figure_title は執筆時点で利用できるリージョンの世界地図を示している. 日本では東京と大阪にデータセンターがある. 各リージョンには固有の ID がついており,例えば東京は ap-northeast-1, 米国オハイオ州は us-east-2,などと定義されている.

Regions in AWS(出典: https://aws.amazon.com/about-aws/global-infrastructure/)

AWS コンソールにログインすると,画面右上のメニューバーでリージョンを選択することができる(figure_title, 赤丸で囲った箇所). EC2, S3 などの AWS のリソースは,リージョンごとに完全に独立である. したがって,リソースを新たにデプロイする際,あるいはデプロイ済みのリソースを閲覧する際は,コンソールのリージョンが正しく設定されているか,確認する必要がある. ウェブビジネスを展開する場合などは,世界の各地にクラウドを展開する必要があるが,個人的な研究用途として用いる場合は,最寄りのリージョン (i.e. 東京) を使えば基本的に問題ない.

AWSコンソールでリージョンを選択

Avaialibity Zone (AZ) とは,リージョン内で地理的に隔離されたデータセンターのことである. それぞれのリージョンは 2 個以上の AZ を有しており,もし一つの AZ で火災や停電などが起きた場合でも,ほかの AZ がその障害をカバーすることができる. また, AZ 間は高速な AWS 専用ネットワーク回線で結ばれているため, AZ 間のデータ転送は極めて早い. AZ は,ビジネスなどでサーバーダウンが許容されない場合などに注意すべき概念であり,個人的な用途で使う限りにおいてはあまり深く考慮する必要はない.言葉の意味だけ知っておけば十分である.

AWS を使用する際,どこのリージョンを指定するのがよいのだろうか? インターネットの接続速度の観点からは,地理的に一番近いリージョンを使用するのが一般的によいだろう. 一方, EC2 の利用料などはリージョンごとに価格設定が若干 (10-20%程度) 異なる. したがって,自分が最も頻繁に利用するサービスの価格が最も安く設定されているリージョンを選択する,というのも重要な視点である. また,いくつかのサービスは,特定のリージョンで利用できない場合もある. これらのポイントから総合的に判断して使用するリージョンを決めると良い.

AWS Educate を利用している読者へ

執筆時点において,AWS Educate による Starter Account を使用している場合は us-east-1 region のみ利用できる (参照).

AWS でのクラウド開発

AWS のクラウドの全体像がわかってきたところで,次のトピックとして,どのようにして AWS 上にクラウドの開発を行い,展開していくかについての概略を解説しよう.

AWS のリソースを追加・編集・削除するなどの操作を実行するには,コンソールを用いる方法と,API を用いる方法の,二つの経路がある.

コンソール画面からリソースを操作する

AWS のアカウントにログインすると,まず最初に表示されるのがAWS コンソールである (figure_title).

AWSマネージメントコンソール画面

コンソールを使うことで, EC2 のインスタンスを立ち上げたり,S3 のデータを追加・削除したり,ログを閲覧したりなど,AWS 上のあらゆるリソースの操作を GUI (Graphical User Interface) を通して実行することができる. 初めて触る機能をポチポチと試したり,デバッグを行うときなどにとても便利である

コンソールはさらっと機能を試したり,開発中のクラウドのデバッグをするときには便利なのであるが,実際にクラウドの開発をする場面でこれを直接いじることはあまりない. むしろ,次に紹介する API を使用して,プログラムとしてクラウドのリソースを記述することで開発を行うのが一般的である. そのような理由で,本書では AWS コンソールを使った AWS の使い方はあまり触れない. AWS のドキュメンテーションには,たくさんの チュートリアル が用意されており,コンソール画面から様々な操作を行う方法が記述されているので,興味がある読者はそちらを参照されたい.

API からリソースを操作する

API (Application Programming Interface) を使うことで,コマンドを AWS に送信し,クラウドのリソースの操作をすることができる. API とは,端的に言えば AWS が公開しているコマンドの一覧であり,GET, POST, DELETE などの REST API から構成されている (REST API については (#sec_rest_api) で簡単に解説する). が,直接 REST API を入力するのは面倒であるので,その手間を解消するための様々なツールが提供されている.

例えば, AWS CLI は, UNIX コンソールから AWS API を実行するための CLI (Command Line Interface) である. CLI に加えて,いろいろなプログラミング言語での SDK (Software Development Kit) が提供されている.以下に一例を挙げる.

具体的な API の使用例を見てみよう.

S3 に新しい保存領域 (Bucket (バケット) とよばれる) を追加したいとしよう. AWS CLI を使った場合は,次のようなコマンドを打てばよい.

sh
$ aws s3 mb s3://my-bucket --region ap-northeast-1
$ aws s3 mb s3://my-bucket --region ap-northeast-1

上記のコマンドは, my-bucket という名前のバケットを, ap-northeast-1 のリージョンに作成する.

Python からこれと同じ操作を実行するには, boto3 ライブラリを使って,次のようなスクリプトを実行する.

python
import boto3

s3_client = boto3.client("s3", region_name="ap-northeast-1")
s3_client.create_bucket(Bucket="my-bucket")
import boto3

s3_client = boto3.client("s3", region_name="ap-northeast-1")
s3_client.create_bucket(Bucket="my-bucket")

もう一つ例をあげよう.

新しい EC2 のインスタンス(インスタンスとは,起動状態にある仮想サーバーの意味である)を起動するには,次のようなコマンドを打てば良い.

sh
$ aws ec2 run-instances --image-id ami-xxxxxxxx --count 1 --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-903004f8 --subnet-id subnet-6e7f829e
$ aws ec2 run-instances --image-id ami-xxxxxxxx --count 1 --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-903004f8 --subnet-id subnet-6e7f829e

このコマンドにより, t2.micro というタイプ (1 vCPU, 1.0 GB RAM) のインスタンスが起動する. ここではその他のパラメータの詳細の説明は省略する (ハンズオン ( (#sec_first_ec2)) で詳しく解説する).

Python から上記と同じ操作を実行するには,以下のようなスクリプトを使う.

python
import boto3

ec2_client = boto3.client("ec2")
ec2_client.run_instances(
    ImageId="ami-xxxxxxxxx",
    MinCount=1,
    MaxCount=1,
    KeyName="MyKeyPair",
    InstanceType="t2.micro",
    SecurityGroupIds=["sg-903004f8"],
    SubnetId="subnet-6e7f829e",
)
import boto3

ec2_client = boto3.client("ec2")
ec2_client.run_instances(
    ImageId="ami-xxxxxxxxx",
    MinCount=1,
    MaxCount=1,
    KeyName="MyKeyPair",
    InstanceType="t2.micro",
    SecurityGroupIds=["sg-903004f8"],
    SubnetId="subnet-6e7f829e",
)

以上の例を通じて,API によるクラウドのリソースの操作のイメージがつかめてきただろうか? コマンド一つで,新しい仮想サーバーを起動したり,データの保存領域を追加したり,任意の操作を実行できるわけである. 基本的に,このようなコマンドを複数組み合わせていくことで,自分の望む CPU・RAM・ネットワーク・ストレージが備わった計算環境を構築することができる. もちろん,逆の操作 (リソースの削除) も API を使って実行できる.

ミニ・ハンズオン: AWS CLI を使ってみよう

ここでは,ミニ・ハンズオンとして,AWS CLI を実際に使ってみる. AWS CLI は先述のとおり, AWS 上の任意のリソースの操作が可能であるが,ここでは一番シンプルな,S3 を使ったファイルの読み書きを実践する (EC2 の操作は少し複雑なので,第一回ハンズオンで行う). aws s3 コマンドの詳しい使い方は 公式ドキュメンテーションを参照.

AWS CLI のインストールについては, (#aws_cli_install) を参照.

以下に紹介するハンズオンは,基本的に S3 の無料枠 の範囲内で実行することができる.

以下のコマンドを実行する前に,AWS の認証情報が正しく設定されていることを確認する. これには ~/.aws/credentials のファイルに設定が書き込まれているか,環境変数 (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION) が定義されている必要がある. 詳しくは (#aws_cli_install) を参照.

まずは,S3 にデータの格納領域 (Bucket とよばれる.一般的な OS での"ドライブ"に相当する) を作成するところから始めよう.

sh
$ bucketName="mybucket-$(openssl rand -hex 12)"
$ echo $bucketName
$ aws s3 mb "s3://${bucketName}"
$ bucketName="mybucket-$(openssl rand -hex 12)"
$ echo $bucketName
$ aws s3 mb "s3://${bucketName}"

S3 のバケットの名前は, AWS 全体で一意的でなければならないことから,前述のコマンドではランダムな文字列を含んだバケットの名前を生成し,bucketName という変数に格納している. そして, aws s3 mb (mb は make bucket の略) によって,新しいバケットを作成する.

次に,バケットの一覧を取得してみよう.

sh
$ aws s3 ls

2020-06-07 23:45:44 mybucket-c6f93855550a72b5b66f5efe
$ aws s3 ls

2020-06-07 23:45:44 mybucket-c6f93855550a72b5b66f5efe

先ほど作成したバケットがリストにあることを確認できる.

本書のノーテーションとして,コマンドラインに入力するコマンドは,それがコマンドであると明示する目的で先頭に $ がつけてある. $ はコマンドをコピー&ペーストするときは除かなければならない. 逆に,コマンドの出力は $ なしで表示されている.

次に,バケットにファイルをアップロードする.

sh
$ echo "Hello world" > hello_world.txt
$ aws s3 cp hello_world.txt "s3://${bucketName}/hello_world.txt"
$ echo "Hello world" > hello_world.txt
$ aws s3 cp hello_world.txt "s3://${bucketName}/hello_world.txt"

上では hello_world.txt というダミーのファイルを作成して,それをアップロードした.

それでは,バケットの中にあるファイルの一覧を取得してみる.

sh
$ aws s3 ls "s3://${bucketName}" --human-readable

2020-06-07 23:54:19   13 Bytes hello_world.txt
$ aws s3 ls "s3://${bucketName}" --human-readable

2020-06-07 23:54:19   13 Bytes hello_world.txt

先ほどアップロードしたファイルがたしかに存在することがわかる.

最後に,使い終わったバケットを削除する.

sh
$ aws s3 rb "s3://${bucketName}" --force
$ aws s3 rb "s3://${bucketName}" --force

rb は remove bucket の略である. デフォルトでは,バケットの中にファイルが存在すると削除できない. 空でないバケットを強制的に削除するには --force のオプションを付ける.

以上のように,AWS CLI を使って S3 バケットに対しての一連の操作を実行できた. EC2 や Lambda, DynamoDB などについても同様に AWS CLI を使ってあらゆる操作を実行できる.

Amazon Resource Name (ARN)

AWS 上のあらゆるリソースには, Amazon Resource Name (ARN) という固有の ID が付与されている. ARN は arn:aws:s3:::my_bucket/ のようなフォーマットで記述され,ARN を使用することで,特定の AWS リソース (S3 のバケットや EC2 のインスタンス) を一意的に参照することができる.

S3 バケットや EC2 インスタンスなどには ARN に加えて,人間が読みやすい名前を定義することも可能である. この場合は,ARN または名前のどちらを用いても同じリソースを参照することが可能である.

CloudFormation と AWS CDK

CloudFormation による Infrastructure as Code (IaC)

前節で述べたように,AWS API を使うことでクラウドのあらゆるリソースの作成・管理が可能である. よって,原理上は, API のコマンドを組み合わせていくことで,自分の作りたいクラウドを設計することができる.

しかし,ここで実用上考慮しなければならない点が一つある. AWS API には大きく分けて,リソースを操作するコマンドと,タスクを実行するコマンドがあることである (figure_title).

AWS APIはリソースを操作するコマンドとタスクを実行するコマンドに大きく分けられる.リソースを記述・管理するのに使われるのが, CloudFormation と CDK である.

リソースを操作するとは,EC2 のインスタンスを起動したり,S3 のバケットを作成したり,データベースに新たなテーブルを追加する,などの静的なリソースを準備する 操作を指す. "ハコ"を作る操作とよんでも良いだろう. このようなコマンドは,クラウドのデプロイ時にのみ,一度だけ実行されればよい

タスクを実行するコマンド とは, EC2 のインスタンスにジョブを投入したり, S3 のバケットにデータを読み書きするなどの操作を指す. これは, EC2 や S3 などのリソース ("ハコ") を前提として,その内部で実行されるべき計算を記述するものである. 前者に比べてこちらは動的な操作を担当する,と捉えることもできる.

そのような観点から,インフラを記述するプログラムタスクを実行するプログラムはある程度分けて管理されるべきである. クラウドの開発は,クラウドの(静的な)リソースを記述するプログラムを作成するステップと,インフラ上で動く動的な操作を行うプログラムを作成するステップの二段階に分けて考えることができる.

AWS での静的リソースを管理するための仕組みが, CloudFormation である. CloudFormation とは, CloudFormation の文法に従ったテキストファイルを使って,AWS のインフラを記述する仕組みである. CloudFormation を使って,たとえば,EC2 のインスタンスをどれくらいのスペックで,何個起動するか,インスタンス間はどのようなネットワークで結び,どのようなアクセス権限を付与するか,などのリソースの要件を逐次的に記述することができる. 一度 CloudFormation ファイルができ上がれば,それにしたがったクラウドシステムをコマンド一つで AWS 上に展開することができる. また,CloudFormation ファイルを交換することで,全く同一のクラウド環境を他者が簡単に再現することも可能になる. このように,本来は物理的な実体のあるハードウェアを,プログラムによって記述し,管理するという考え方を,**Infrastructure as Code (IaC)**とよぶ.

CloudFormation を記述するには,基本的に JSON (JavaScript Object Notation) とよばれるフォーマットを使う. 次のコードは,JSON で記述された CloudFormation ファイルの一例 (抜粋) である.

json
"Resources" : {
  ...
  "WebServer": {
    "Type" : "AWS::EC2::Instance",
    "Properties": {
      "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" },
                        { "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" }, "Arch" ] } ] },
      "InstanceType"   : { "Ref" : "InstanceType" },
      "SecurityGroups" : [ {"Ref" : "WebServerSecurityGroup"} ],
      "KeyName"        : { "Ref" : "KeyName" },
      "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [
                     "#!/bin/bash -xe\n",
                     "yum update -y aws-cfn-bootstrap\n",

                     "/opt/aws/bin/cfn-init -v ",
                     "         --stack ", { "Ref" : "AWS::StackName" },
                     "         --resource WebServer ",
                     "         --configsets wordpress_install ",
                     "         --region ", { "Ref" : "AWS::Region" }, "\n",

                     "/opt/aws/bin/cfn-signal -e $? ",
                     "         --stack ", { "Ref" : "AWS::StackName" },
                     "         --resource WebServer ",
                     "         --region ", { "Ref" : "AWS::Region" }, "\n"
      ]]}}
    },
    ...
  },
  ...
},
"Resources" : {
  ...
  "WebServer": {
    "Type" : "AWS::EC2::Instance",
    "Properties": {
      "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" },
                        { "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" }, "Arch" ] } ] },
      "InstanceType"   : { "Ref" : "InstanceType" },
      "SecurityGroups" : [ {"Ref" : "WebServerSecurityGroup"} ],
      "KeyName"        : { "Ref" : "KeyName" },
      "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [
                     "#!/bin/bash -xe\n",
                     "yum update -y aws-cfn-bootstrap\n",

                     "/opt/aws/bin/cfn-init -v ",
                     "         --stack ", { "Ref" : "AWS::StackName" },
                     "         --resource WebServer ",
                     "         --configsets wordpress_install ",
                     "         --region ", { "Ref" : "AWS::Region" }, "\n",

                     "/opt/aws/bin/cfn-signal -e $? ",
                     "         --stack ", { "Ref" : "AWS::StackName" },
                     "         --resource WebServer ",
                     "         --region ", { "Ref" : "AWS::Region" }, "\n"
      ]]}}
    },
    ...
  },
  ...
},

ここでは, "WebServer" という名前のつけられた EC2 インスタンスを定義している.かなり長大で複雑な記述であるが,これによって所望のスペック・OS をもつ EC2 インスタンスを自動的に生成することが可能になる.

AWS CDK

前節で紹介した CloudFormation は,見てわかるとおり大変記述が複雑であり,またそれのどれか一つにでも誤りがあってはいけない. また,基本的に"テキスト"を書いていくことになるので,プログラミング言語で使うような変数やクラスといった便利な概念が使えない (厳密には, CloudFormation にも変数に相当するような機能は存在する). また,記述の多くの部分は繰り返しが多く,自動化できる部分も多い.

そのような悩みを解決してくれるのが, AWS Cloud Development Kit (CDK) である. CDK は Python などのプログラミング言語を使って CloudFormation を自動的に生成してくれるツールである. CDK は 2019 年にリリースされたばかりの比較的新しいツールで,日々改良が進められている (GitHub リポジトリ のリリースを見ればその開発のスピードの速さがわかるだろう). CDK は TypeScript (JavaScript), Python, Java など複数の言語でサポートされている.

CDK を使うことで,CloudFormation に相当するクラウドリソースの記述を,より親しみのあるプログラミング言語を使って行うことができる. かつ,典型的なリソース操作に関してはパラメータの多くの部分を自動で決定してくれるので,記述しなければならない量もかなり削減される.

以下に Python を使った CDK のコードの一例 (抜粋) を示す.

python
from aws_cdk import (
    core,
    aws_ec2 as ec2,
)

class MyFirstEc2(core.Stack):

    def __init__(self, scope, name, **kwargs):
        super().__init__(scope, name, **kwargs)

        vpc = ec2.Vpc(
            ... # some parameters
        )

        sg = ec2.SecurityGroup(
            ... # some parameters
        )

        host = ec2.Instance(
            self, "MyGreatEc2",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ec2.MachineImage.latest_amazon_linux(),
            vpc=vpc,
            ...
        )
from aws_cdk import (
    core,
    aws_ec2 as ec2,
)

class MyFirstEc2(core.Stack):

    def __init__(self, scope, name, **kwargs):
        super().__init__(scope, name, **kwargs)

        vpc = ec2.Vpc(
            ... # some parameters
        )

        sg = ec2.SecurityGroup(
            ... # some parameters
        )

        host = ec2.Instance(
            self, "MyGreatEc2",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ec2.MachineImage.latest_amazon_linux(),
            vpc=vpc,
            ...
        )

このコードは,一つ前に示した JSON を使った CloudFormation と実質的に同じことを記述している. とても煩雑だった CloudFormation ファイルに比べて, CDK と Python を使うことで格段に短く,わかりやすく記述できることができるのがわかるだろう.

本書の主題は,CDK を使って,コードを書きながら AWS の概念や開発方法を学んでいくことである. 後の章では CDK を使って様々なハンズオンを実施していく. 早速,最初のハンズオンでは, CDK を使って EC2 インスタンスを作成する方法を学んでいこう.

  • AWS CDK Examples: CDK を使ったプロジェクトの例が多数紹介されている. ここにある例をテンプレートに自分のアプリケーションの開発を進めるとよい.
]]>
<![CDATA[まとめ ]]> https://note.toshiki.dev/development/aws/closing https://note.toshiki.dev/development/aws/closing Thu, 01 Jul 2021 00:00:00 GMT まとめ ]]> まとめ ]]> <![CDATA[クラウド概論 ]]> https://note.toshiki.dev/development/aws/cloud https://note.toshiki.dev/development/aws/cloud Thu, 01 Jul 2021 00:00:00 GMT クラウド概論

クラウドとは?

Cloud

クラウドとはなにか? クラウドという言葉は,それ自身がとても広い意味をもつので,厳密な定義付けを行うことは難しい.

学術的な意味でのクラウドの定義づけをするとしたら,NIST(米国・国立標準技術研究所) による The NIST Definition of Cloud Computing が引用されることが多い. ここに記載されたクラウドの定義・モデルを図示したのが figure_title である.

The NIST Definition of Cloud Computing

これによると,クラウドとは以下の要件が満たされたハードウェア/ソフトウェアの総体のことをいう.

  • On-demand self-service 利用者のリクエストに応じて計算資源が自動的に割り当てられる.

  • Broad network access 利用者はネットワークを通じてクラウドにアクセスできる.

  • Resource pooling クラウドプロバイダーは,所有する計算資源を分割することで複数の利用者に計算資源を割り当てる.

  • Rapid elasticity 利用者のリクエストに応じて,迅速に計算資源の拡大あるいは縮小を行うことができる.

  • Measured service 計算資源の利用量を計測・監視することができる.

…と,いわれても抽象的でよくわからないかもしれない.もう少し具体的な話をする.

個人が所有する計算機で, CPU をアップグレードしようと思ったら,物理的に筐体を開け,CPU ソケットを露出させ,新しい CPU に交換する必要があるだろう. あるいは,ストレージがいっぱいになってしまったら,古いディスクを抜き取り,新しいディスクを挿入する必要がある. 計算機の場所を移動させたときには,新しい部屋の LAN ケーブルを差し込まないとネットワークには接続できない.

クラウドでは,これらの操作がプログラムからのコマンドによって実行できる. CPU が 1000 個欲しいと思ったならば,そのようにクラウドプロバイダーにリクエストを送れば良い. すると,数分もしないうちに 1000 CPU の計算資源が割り当てられる. ストレージを 1TB から 10TB に拡張しようと思ったならば,そのようにコマンドを送ればよい (これは,Google Drive や Dropbox などのサービスなどで馴染みのある人も多いだろう). 計算資源を使い終わったら,そのことをプロバイダーに伝えれば,割り当て分はすぐさま削除される. クラウドプロバイダーは,使った計算資源の量を正確にモニタリングしており,その量をもとに利用料金の計算が行われる.

このように,クラウドの本質は物理的なハードウェアの仮想化・抽象化であり,利用者はコマンドを通じて,まるでソフトウェアの一部かのように,物理的なハードウェアの管理・運用を行うことができる. もちろん,背後では,データセンターに置かれた膨大な数の計算機が大量の電力を消費しながら稼働している. クラウドプロバイダーはデータセンターの計算資源を上手にやりくりし,ソフトウェアとしてのインターフェースをユーザーに提供することで,このような仮想化・抽象化を達成しているわけである. クラウドプロバイダーの視点からすると,大勢のユーザーに計算機を貸し出し,データセンターの稼働率を常時 100%に近づけることで,利益率の最大化を図っているのである.

著者の言葉で,クラウドの重要な特性を定義するならば,以下のようになる.

クラウドとは計算機ハードウェアの抽象化である.つまり,物理的なハードウェアをソフトウェアの一部かのように自在に操作・拡大・接続することを可能にする技術である.

先述の The NIST Definition of Cloud Computing に戻ると,クラウドプロバイダーによるクラウドサービスの形態としては,次の三つが定義されている (figure_title).

  • Software as a Service (SaaS): クラウド上で実行されるアプリケーションをサービスとして利用者に提供する形態. 例として, Google Drive や Slack などが挙げられる. 利用者は,背後にあるクラウドのインフラ (ネットワークやサーバーなど) には直接触れず,アプリケーションとして提供されているクラウドサービスを享受する.

  • Platform as a Service (PaaS): 顧客の作成したアプリケーション (多くの場合データベースと API リクエスト処理を行うサーバーのコードから構成される) をデプロイする環境をサービスとして利用者に提供する形態. PaaS では利用者はクラウドのインフラに直接触れることはなく,計算負荷が増減した際のサーバーのスケーリングはクラウドプロバイダーによってなされる. 例としては, Google App Engine や Heroku などがある.

  • Infrastructure as a Service (IaaS): クラウド上の計算インフラストラクチャーを従量課金制で利用者に提供する形態. 利用者は必要なネットワーク・サーバー・ストレージをプロバイダーから借り受け,そこに自身のアプリケーションを展開し運用する. IaaS の例としては AWS EC2 などが挙げられる.

本書が扱うのは,主に IaaS におけるクラウド開発である. すなわち,開発者がクラウドのインフラを直接操作し,所望のネットワーク・サーバー・ストレージなどを一から構成し,そこにアプリケーションを展開するというクラウド開発である. この意味において,クラウドの開発とはクラウドインフラストラクチャーを定義・展開するプログラムを構築するステップインフラ上で実際に走るアプリケーションを作成するステップの二つに分けることができる. この二つは,プログラマーの技術としてはある程度分業を行うことが可能であるが,最も効率化・最適化されたクラウドシステムを構築するためには両方の理解が必須である. 本書では,前者 (クラウドインフラの記述) に重きを置きつつ,アプリケーションレイヤーの話題も取り扱う. PaaS とは,開発者はアプリケーションレイヤーの開発に注力し,クラウドインフラの部分はクラウドプロバイダーに依存するという概念である. PaaS は,クラウドインフラの開発が不要になることで開発の時間が短縮されるが,細かなインフラの挙動はコントロールできないという限界がある. 本書では PaaS についてはとくに取り扱わない.

SaaS は本書の文脈では開発による"成果物"と捉えられるだろう. すなわち, IaaS を構成するプログラムを作成し展開することによって,一般の人が利用できるようなウェブ上の計算サービスやデータベースを提供することが開発の最終ゴールである. 本書のハンズオンではその実例として,シンプルな SNS の作成 ( (#sec_bashoutter)) などの演習を提供する.

なお,最近では Function as a Service (FaaS) やサーバーレスコンピューティングなども新たなクラウドのカテゴリとして認知されている. これらの概念については (#sec_intro_serverless) などの章で詳しく触れていく. 本書を読み進める中で明らかになるように,クラウドの技術は日進月歩である. 本書では実用的・教育的な観点から,従来的なクラウドの設計概念に触れたあと,サーバーレスなどの最新の技術も網羅するので,楽しみにしながら読み進めていただきたい.

最後に,The NIST Definition of Cloud Computing によると,クラウドの運用形態について次のような定義がなされている (figure_title). 特定の組織・団体・企業の内部のみで使用されるクラウドを,プライベートクラウド (private cloud) とよぶ. 例えば,大学や研究機関では,その機関の構成員向けの大規模計算機サーバーが運用されていることが多い. プライベートクラウドは,組織の構成員ならば無料もしくは極めて割安のコストで計算を実行できる. しかし,使用できる計算資源の上限は限られる場合が多く,拡張時の柔軟性に欠ける場合もある.

一方,商用のサービスとして一般の顧客に向けたクラウドのことを,パブリッククラウド (public cloud) とよぶ. 有名なパブリッククラウドプラットフォームの例を挙げると, Google 社が提供する Google Cloud Platform (GCP), Microsoft 社が提供する Azure, Amazon 社が提供する Amazon Web Services (AWS) などがある. パブリッククラウドを利用する場合は,プロバイダーの設定した利用料金を支払うことになる. その分,巨大なデータセンターを運用する企業の計算資源にアクセスすることができるので,計算のキャパシティは無尽蔵にあるといって過言でない.

第三のクラウドの運用形態として,コミュニティクラウド (community cloud) が挙げられる. これは,例えば政府の省庁・機関など目的・役割を共有する団体・組織が共有して運用するクラウドを指す. 最後に,ハイブリッドクラウド (hybrid cloud) という形態もあり,これはプライベート・パブリック・コミュニティクラウドの二つ以上の組み合わせによって構成されるクラウドのことである. データ保護の観点から,いくつかの機密データやプライバシーに関わる情報はプライベートクラウドに保持し,残りのシステムをパブリッククラウドに依存する,などの形態が想定される.

本書で説明するのは,基本的にパブリッククラウドを使ったクラウド開発である. 特に,Amazon Web Services (AWS) を使用して,具体的な技術と概念を学んでいく. 一方で,サーバーのスケーリングや仮想計算環境などのテクニックはすべてのクラウドに共通な概念であるので,クラウドのプラットフォームが変わろうと一般に通用する知識も同時に身につくはずだ.

なぜクラウドを使うのか?

上述のように,クラウドとはプログラムを通じて自由に計算資源を操作することのできる計算環境である. ここでは,リアルなローカル計算環境と比べて,なぜクラウドを使うと良いことがあるのかについて述べたい.

  1. 自由にサーバーのサイズをスケールできる

    なにか新しいプロジェクトを始めるとき,あらかじめ必要なサーバーのスペックを知るのは難しい. いきなり大きなサーバーを買うのはリスクが高い. 一方で,小さすぎるサーバーでは,後のアップグレードが面倒である. クラウドを利用すれば,プロジェクトを進めながら,必要な分だけの計算資源を確保することができる. 2. 自分でサーバーをメンテナンスする必要がない

    悲しいことに,コンピュータとは古くなるものである.最近の技術の進歩の速度からすると,5 年も経てば,もはや当時の最新コンピュータも化石と同じである. 5 年ごとにサーバーを入れ替えるのは相当な手間である. またサーバーの停電や故障など不意の障害への対応も必要である. クラウドでは,そのようなインフラの整備やメンテナンスはプロバイダーが自動でやってくれるので,ユーザーが心配する必要がない. 3. 初期コスト 0

    自前の計算環境とクラウドの,経済的なコストのイメージを示したのが figure_title である. クラウドを利用する場合の初期コストは基本的に 0 である. その後,使った利用量に応じてコストが増大していく. 一方,自前の計算環境では,大きな初期コストが生じる. その分,初期投資後のコストの増加は,電気利用料やサーバー維持費などに留まるため,クラウドを利用した場合よりも傾きは小さくなる. 自前の計算機では,ある一定期間後,サーバーのアップグレードなどによる支出が生じることがある. 一方,クラウドを利用する場合は,そのような非連続なコストの増大は基本的に生じない. クラウドのコストのカーブが,自前計算環境のコストのカーブの下にある範囲においては,クラウドを使うことは経済的なコスト削減につながる.

    クラウドと自前計算機環境の経済的コストの比較

とくに,**1.**の点は研究の場面では重要であると筆者は感じる. 研究をやっていて,四六時中計算を走らせ続けるという場合は少ない. むしろ,新しいアルゴリズムが完成したとき・新しいデータが届いたとき,集中的・突発的に計算タスクが増大することが多いだろう. そういったときに,フレキシブルに計算力を増強させることができるのは,クラウドを使う大きなメリットである.

ここまでクラウドを使うメリットを述べたが,逆に,デメリットというのも当然存在する.

  1. クラウドは賢く使わないといけない

    figure_title で示したコストのカーブにあるとおり,使い方によっては自前の計算環境のほうがコスト的に有利な場面は存在しうる. クラウドを利用する際は,使い終わった計算資源はすぐに削除するなど,利用者が賢く管理を行う必要があり,これを怠ると思いもしない額の請求が届く可能性がある. 2. セキュリティ

    クラウドは,インターネットを通じて世界のどこからでもアクセスできる状態にあり,セキュリティ管理を怠ると簡単にハッキングの対象となりうる. ハッキングを受けると,情報流出だけでなく,経済的な損失を被る可能性がある. 3. ラーニングカーブ

    上記のように,コスト・セキュリティなど,クラウドを利用する際に留意しなければならない点は多い. 賢くクラウドを使うには,十分なクラウドの理解が必要であり,そのラーニングカーブを乗り越える必要がある.

Mac/Linux などでコマンドを入力するときに使用する,あの黒い画面のことを Terminal とよんだりする. この言葉の語源をご存知だろうか?

Terminal

この言葉の語源は,コンピュータが誕生して間もない頃の時代に遡る. その頃のコンピュータというと,何千何万のという数の真空管が接続された,会議室一個分くらいのサイズのマシンであった. そのような高価でメンテが大変な機材であるから,当然みんなでシェアして使うことが前提となる. ユーザーがコンピュータにアクセスするため,マシンからは何本かのケーブルが伸び,それぞれにキーボードとスクリーンが接続されていた… これを Terminal とよんでいたのである. 人々は,代わる代わる Terminal の前に座って,計算機との対話を行っていた.

時代は流れ,Windows や Mac などのいわゆるパーソナルコンピュータの出現により,コンピュータはみんなで共有するものではなく,個人が所有するものになった.

最近のクラウドの台頭は,みんなで大きなコンピュータをシェアするという,最初のコンピュータの使われ方に原点回帰していると捉えることもできる. 一方で,スマートフォンやウェアラブルなどのエッジデバイスの普及も盛んであり,個人が複数の"小さな"コンピュータを所有する,という流れも同時に進行しているのである.

]]>
クラウド概論

クラウドとは?

Cloud

クラウドとはなにか? クラウドという言葉は,それ自身がとても広い意味をもつので,厳密な定義付けを行うことは難しい.

学術的な意味でのクラウドの定義づけをするとしたら,NIST(米国・国立標準技術研究所) による The NIST Definition of Cloud Computing が引用されることが多い. ここに記載されたクラウドの定義・モデルを図示したのが figure_title である.

The NIST Definition of Cloud Computing

これによると,クラウドとは以下の要件が満たされたハードウェア/ソフトウェアの総体のことをいう.

  • On-demand self-service 利用者のリクエストに応じて計算資源が自動的に割り当てられる.

  • Broad network access 利用者はネットワークを通じてクラウドにアクセスできる.

  • Resource pooling クラウドプロバイダーは,所有する計算資源を分割することで複数の利用者に計算資源を割り当てる.

  • Rapid elasticity 利用者のリクエストに応じて,迅速に計算資源の拡大あるいは縮小を行うことができる.

  • Measured service 計算資源の利用量を計測・監視することができる.

…と,いわれても抽象的でよくわからないかもしれない.もう少し具体的な話をする.

個人が所有する計算機で, CPU をアップグレードしようと思ったら,物理的に筐体を開け,CPU ソケットを露出させ,新しい CPU に交換する必要があるだろう. あるいは,ストレージがいっぱいになってしまったら,古いディスクを抜き取り,新しいディスクを挿入する必要がある. 計算機の場所を移動させたときには,新しい部屋の LAN ケーブルを差し込まないとネットワークには接続できない.

クラウドでは,これらの操作がプログラムからのコマンドによって実行できる. CPU が 1000 個欲しいと思ったならば,そのようにクラウドプロバイダーにリクエストを送れば良い. すると,数分もしないうちに 1000 CPU の計算資源が割り当てられる. ストレージを 1TB から 10TB に拡張しようと思ったならば,そのようにコマンドを送ればよい (これは,Google Drive や Dropbox などのサービスなどで馴染みのある人も多いだろう). 計算資源を使い終わったら,そのことをプロバイダーに伝えれば,割り当て分はすぐさま削除される. クラウドプロバイダーは,使った計算資源の量を正確にモニタリングしており,その量をもとに利用料金の計算が行われる.

このように,クラウドの本質は物理的なハードウェアの仮想化・抽象化であり,利用者はコマンドを通じて,まるでソフトウェアの一部かのように,物理的なハードウェアの管理・運用を行うことができる. もちろん,背後では,データセンターに置かれた膨大な数の計算機が大量の電力を消費しながら稼働している. クラウドプロバイダーはデータセンターの計算資源を上手にやりくりし,ソフトウェアとしてのインターフェースをユーザーに提供することで,このような仮想化・抽象化を達成しているわけである. クラウドプロバイダーの視点からすると,大勢のユーザーに計算機を貸し出し,データセンターの稼働率を常時 100%に近づけることで,利益率の最大化を図っているのである.

著者の言葉で,クラウドの重要な特性を定義するならば,以下のようになる.

クラウドとは計算機ハードウェアの抽象化である.つまり,物理的なハードウェアをソフトウェアの一部かのように自在に操作・拡大・接続することを可能にする技術である.

先述の The NIST Definition of Cloud Computing に戻ると,クラウドプロバイダーによるクラウドサービスの形態としては,次の三つが定義されている (figure_title).

  • Software as a Service (SaaS): クラウド上で実行されるアプリケーションをサービスとして利用者に提供する形態. 例として, Google Drive や Slack などが挙げられる. 利用者は,背後にあるクラウドのインフラ (ネットワークやサーバーなど) には直接触れず,アプリケーションとして提供されているクラウドサービスを享受する.

  • Platform as a Service (PaaS): 顧客の作成したアプリケーション (多くの場合データベースと API リクエスト処理を行うサーバーのコードから構成される) をデプロイする環境をサービスとして利用者に提供する形態. PaaS では利用者はクラウドのインフラに直接触れることはなく,計算負荷が増減した際のサーバーのスケーリングはクラウドプロバイダーによってなされる. 例としては, Google App Engine や Heroku などがある.

  • Infrastructure as a Service (IaaS): クラウド上の計算インフラストラクチャーを従量課金制で利用者に提供する形態. 利用者は必要なネットワーク・サーバー・ストレージをプロバイダーから借り受け,そこに自身のアプリケーションを展開し運用する. IaaS の例としては AWS EC2 などが挙げられる.

本書が扱うのは,主に IaaS におけるクラウド開発である. すなわち,開発者がクラウドのインフラを直接操作し,所望のネットワーク・サーバー・ストレージなどを一から構成し,そこにアプリケーションを展開するというクラウド開発である. この意味において,クラウドの開発とはクラウドインフラストラクチャーを定義・展開するプログラムを構築するステップインフラ上で実際に走るアプリケーションを作成するステップの二つに分けることができる. この二つは,プログラマーの技術としてはある程度分業を行うことが可能であるが,最も効率化・最適化されたクラウドシステムを構築するためには両方の理解が必須である. 本書では,前者 (クラウドインフラの記述) に重きを置きつつ,アプリケーションレイヤーの話題も取り扱う. PaaS とは,開発者はアプリケーションレイヤーの開発に注力し,クラウドインフラの部分はクラウドプロバイダーに依存するという概念である. PaaS は,クラウドインフラの開発が不要になることで開発の時間が短縮されるが,細かなインフラの挙動はコントロールできないという限界がある. 本書では PaaS についてはとくに取り扱わない.

SaaS は本書の文脈では開発による"成果物"と捉えられるだろう. すなわち, IaaS を構成するプログラムを作成し展開することによって,一般の人が利用できるようなウェブ上の計算サービスやデータベースを提供することが開発の最終ゴールである. 本書のハンズオンではその実例として,シンプルな SNS の作成 ( (#sec_bashoutter)) などの演習を提供する.

なお,最近では Function as a Service (FaaS) やサーバーレスコンピューティングなども新たなクラウドのカテゴリとして認知されている. これらの概念については (#sec_intro_serverless) などの章で詳しく触れていく. 本書を読み進める中で明らかになるように,クラウドの技術は日進月歩である. 本書では実用的・教育的な観点から,従来的なクラウドの設計概念に触れたあと,サーバーレスなどの最新の技術も網羅するので,楽しみにしながら読み進めていただきたい.

最後に,The NIST Definition of Cloud Computing によると,クラウドの運用形態について次のような定義がなされている (figure_title). 特定の組織・団体・企業の内部のみで使用されるクラウドを,プライベートクラウド (private cloud) とよぶ. 例えば,大学や研究機関では,その機関の構成員向けの大規模計算機サーバーが運用されていることが多い. プライベートクラウドは,組織の構成員ならば無料もしくは極めて割安のコストで計算を実行できる. しかし,使用できる計算資源の上限は限られる場合が多く,拡張時の柔軟性に欠ける場合もある.

一方,商用のサービスとして一般の顧客に向けたクラウドのことを,パブリッククラウド (public cloud) とよぶ. 有名なパブリッククラウドプラットフォームの例を挙げると, Google 社が提供する Google Cloud Platform (GCP), Microsoft 社が提供する Azure, Amazon 社が提供する Amazon Web Services (AWS) などがある. パブリッククラウドを利用する場合は,プロバイダーの設定した利用料金を支払うことになる. その分,巨大なデータセンターを運用する企業の計算資源にアクセスすることができるので,計算のキャパシティは無尽蔵にあるといって過言でない.

第三のクラウドの運用形態として,コミュニティクラウド (community cloud) が挙げられる. これは,例えば政府の省庁・機関など目的・役割を共有する団体・組織が共有して運用するクラウドを指す. 最後に,ハイブリッドクラウド (hybrid cloud) という形態もあり,これはプライベート・パブリック・コミュニティクラウドの二つ以上の組み合わせによって構成されるクラウドのことである. データ保護の観点から,いくつかの機密データやプライバシーに関わる情報はプライベートクラウドに保持し,残りのシステムをパブリッククラウドに依存する,などの形態が想定される.

本書で説明するのは,基本的にパブリッククラウドを使ったクラウド開発である. 特に,Amazon Web Services (AWS) を使用して,具体的な技術と概念を学んでいく. 一方で,サーバーのスケーリングや仮想計算環境などのテクニックはすべてのクラウドに共通な概念であるので,クラウドのプラットフォームが変わろうと一般に通用する知識も同時に身につくはずだ.

なぜクラウドを使うのか?

上述のように,クラウドとはプログラムを通じて自由に計算資源を操作することのできる計算環境である. ここでは,リアルなローカル計算環境と比べて,なぜクラウドを使うと良いことがあるのかについて述べたい.

  1. 自由にサーバーのサイズをスケールできる

    なにか新しいプロジェクトを始めるとき,あらかじめ必要なサーバーのスペックを知るのは難しい. いきなり大きなサーバーを買うのはリスクが高い. 一方で,小さすぎるサーバーでは,後のアップグレードが面倒である. クラウドを利用すれば,プロジェクトを進めながら,必要な分だけの計算資源を確保することができる. 2. 自分でサーバーをメンテナンスする必要がない

    悲しいことに,コンピュータとは古くなるものである.最近の技術の進歩の速度からすると,5 年も経てば,もはや当時の最新コンピュータも化石と同じである. 5 年ごとにサーバーを入れ替えるのは相当な手間である. またサーバーの停電や故障など不意の障害への対応も必要である. クラウドでは,そのようなインフラの整備やメンテナンスはプロバイダーが自動でやってくれるので,ユーザーが心配する必要がない. 3. 初期コスト 0

    自前の計算環境とクラウドの,経済的なコストのイメージを示したのが figure_title である. クラウドを利用する場合の初期コストは基本的に 0 である. その後,使った利用量に応じてコストが増大していく. 一方,自前の計算環境では,大きな初期コストが生じる. その分,初期投資後のコストの増加は,電気利用料やサーバー維持費などに留まるため,クラウドを利用した場合よりも傾きは小さくなる. 自前の計算機では,ある一定期間後,サーバーのアップグレードなどによる支出が生じることがある. 一方,クラウドを利用する場合は,そのような非連続なコストの増大は基本的に生じない. クラウドのコストのカーブが,自前計算環境のコストのカーブの下にある範囲においては,クラウドを使うことは経済的なコスト削減につながる.

    クラウドと自前計算機環境の経済的コストの比較

とくに,**1.**の点は研究の場面では重要であると筆者は感じる. 研究をやっていて,四六時中計算を走らせ続けるという場合は少ない. むしろ,新しいアルゴリズムが完成したとき・新しいデータが届いたとき,集中的・突発的に計算タスクが増大することが多いだろう. そういったときに,フレキシブルに計算力を増強させることができるのは,クラウドを使う大きなメリットである.

ここまでクラウドを使うメリットを述べたが,逆に,デメリットというのも当然存在する.

  1. クラウドは賢く使わないといけない

    figure_title で示したコストのカーブにあるとおり,使い方によっては自前の計算環境のほうがコスト的に有利な場面は存在しうる. クラウドを利用する際は,使い終わった計算資源はすぐに削除するなど,利用者が賢く管理を行う必要があり,これを怠ると思いもしない額の請求が届く可能性がある. 2. セキュリティ

    クラウドは,インターネットを通じて世界のどこからでもアクセスできる状態にあり,セキュリティ管理を怠ると簡単にハッキングの対象となりうる. ハッキングを受けると,情報流出だけでなく,経済的な損失を被る可能性がある. 3. ラーニングカーブ

    上記のように,コスト・セキュリティなど,クラウドを利用する際に留意しなければならない点は多い. 賢くクラウドを使うには,十分なクラウドの理解が必要であり,そのラーニングカーブを乗り越える必要がある.

Mac/Linux などでコマンドを入力するときに使用する,あの黒い画面のことを Terminal とよんだりする. この言葉の語源をご存知だろうか?

Terminal

この言葉の語源は,コンピュータが誕生して間もない頃の時代に遡る. その頃のコンピュータというと,何千何万のという数の真空管が接続された,会議室一個分くらいのサイズのマシンであった. そのような高価でメンテが大変な機材であるから,当然みんなでシェアして使うことが前提となる. ユーザーがコンピュータにアクセスするため,マシンからは何本かのケーブルが伸び,それぞれにキーボードとスクリーンが接続されていた… これを Terminal とよんでいたのである. 人々は,代わる代わる Terminal の前に座って,計算機との対話を行っていた.

時代は流れ,Windows や Mac などのいわゆるパーソナルコンピュータの出現により,コンピュータはみんなで共有するものではなく,個人が所有するものになった.

最近のクラウドの台頭は,みんなで大きなコンピュータをシェアするという,最初のコンピュータの使われ方に原点回帰していると捉えることもできる. 一方で,スマートフォンやウェアラブルなどのエッジデバイスの普及も盛んであり,個人が複数の"小さな"コンピュータを所有する,という流れも同時に進行しているのである.

]]>
<![CDATA[Docker 入門 ]]> https://note.toshiki.dev/development/aws/docker-system https://note.toshiki.dev/development/aws/docker-system Thu, 01 Jul 2021 00:00:00 GMT Docker 入門

ここまでの章で扱ってきたハンズオンでは,単一のサーバーを立ち上げ,それに SSH でログインをして,コマンドを叩くことで計算を行ってきた. いわば,パーソナルコンピュータの延長のような形でクラウドを使ってきたわけである. このような,インターネットのどこからでもアクセスできるパーソナルコンピュータとしてのクラウドという使い方も,もちろん便利であるし,いろいろな応用の可能性がある. しかし,これだけではクラウドの本当の価値は十分に発揮されていないと言うべきだろう. (#chap_cloud_basics) で述べたように,現代的なクラウドの一番の強みは自由に計算機の規模を拡大できることにある. すなわち,多数のサーバーを同時に起動し,複数のジョブを分散並列的に実行させることで大量のデータを処理してこそ,クラウドの本領が発揮されるのである.

本章からはじまる 3 章分 (Docker 入門, (#sec_fargate_qabot), (#sec_aws_batch)) を使って,クラウドを利用することでどのように大規模な計算システムを構築しビッグデータの解析に立ち向かうのか,その片鱗をお見せしたい. とくに,前章で扱った深層学習をどのようにビッグデータに適用していくかという点に焦点を絞って議論していきたい. そのための前準備として,本章では Docker とよばれる計算機環境の仮想化ソフトウェアを紹介する (figure_title). 現代のクラウドは Docker なしには成り立たないといっても過言ではないだろう. クラウドに限らず,ローカルで行う計算処理にも Docker は大変便利である. AWS からは少し話が離れるが,しっかりと理解して前に進んでもらいたい.

機械学習の大規模化

先ほどから"計算システムの大規模化"と繰り返し唱えているが,それは具体的にはどのようなものを指しているのか? ここでは大規模データを処理するための計算機システムを,機械学習を例にとって見てみよう.

(#sec_scientific_computing) で紹介した GPT-3 のような,超巨大な数のパラメータを有する深層学習モデルを学習させたいとしよう. そのような計算を行いたい場合,一つのサーバーでは計算力が到底足りない. したがって,典型的には figure_title に示すような計算システムの設計がなされる. すなわち,大量の教師データを小さなチャンクとして複数のマシンに分散し,並列的にニューラルネットのパラメータを最適化していくという構造である.

複数の計算機を使った大規模な深層学習モデルの訓練

あるいは,学習済みのモデルを大量のデータに適用し,解析を行いたいとしよう. たとえば, SNS のプラットフォームで大量の画像が与えられて,それぞれの写真に何が写っているのかをラベルづけする,などのアプリケーションを想定できる. そのような場合は, figure_title のようなアーキテクチャが考えられるだろう. すなわち,大量のデータを複数のマシンで分割し,それぞれのマシンで推論の計算を行うというような構造である.

複数の計算機による深層学習モデルを使った推論計算

このような複数の計算機を同時に走らせるようなアプリケーションをクラウド上で実現するには,どのようにすればよいのだろうか?

重要なポイントとして, figure_titlefigure_title で起動している複数のマシンは,基本的に全く同一の OS・計算環境を有している点である. ここで,個人のコンピュータで行うようなインストールの操作を,各マシンで行うこともできるが,それは大変な手間であるし,メンテナンスも面倒だろう. すなわち,大規模な計算システムを構築するには,簡単に計算環境を複製できるような仕組みが必要であるということがわかる.

そのような目的を実現するために使われるのが, Docker とよばれるソフトウェアである.

Docker とは

Docker のアイコン

Docker とは, コンテナ (Container) とよばれる仮想環境下で,ホスト OS とは独立した別の計算環境を走らせるためのソフトウェアである. Docker を使うことで, OS を含めたすべてのプログラムをコンパクトにパッケージングすることが可能になる (パッケージされた一つの計算環境のことを **イメージ (Image)**とよぶ). Docker を使うことで,クラウドのサーバー上に瞬時に計算環境を複製することが可能になり, figure_title で見たような複数の計算機を同時に走らせるためのシステムが実現できる.

Docker は 2013 年に Solomon Hykes らを中心に開発され,それ以降爆発的に普及し,クラウドコンピューティングだけでなく,機械学習・科学計算の文脈などでも欠かすことのできないソフトウェアとなった. Docker はエンタープライズ向けの製品を除き無料で使用することができ,コアの部分は オープンソースプロジェクト として公開されている. Docker は Linux, Windows, Mac いずれの OS でも提供されている. 概念としては, Docker は仮想マシン (Virtual machine; VM) にとても近い. ここでは, VM との対比をしながら,Docker とはなにかを簡単に説明しよう.

仮想マシン (VM) とは,ホストとなるマシンの上に,仮想化された OS を走らせる技術である (figure_title). VM には ハイパーバイザー (Hypervisor) とよばれるレイヤーが存在する. Hypervisor はまず,物理的な計算機リソース (CPU, RAM, network など) を分割し,仮想化する. たとえば, ホストマシンに物理的な CPU が 4 コアあるとして,ハイパーバイザーはそれを (2,2) 個の組に仮想的に分割することができる. VM 上で起動する OS には,ハイパーバイザーによって仮想化されたハードウェアが割り当てられる. VM 上で起動する OS は基本的に完全に独立であり,たとえば OS-A は OS-B に割り当てられた CPU やメモリー領域にアクセスすることはできない (これを isolation とよぶ). VM を作成するための有名なソフトウェアとしては, VMwareVirtualBoxXen などがある. また,これまで触ってきた EC2 も,基本的に VM 技術を使うことで所望のスペックをもった仮想マシンがユーザーに提示される.

Docker も, VM と同様に,仮想化された OS をホストの OS 上に走らせるための技術である. VM に対し, Docker ではハードウェアレベルの仮想化は行われておらず,すべての仮想化はソフトウェアレベルで実現されている (figure_title). Docker で走る仮想 OS は,多くの部分をホストの OS に依存しており,結果として非常にコンパクトである. その結果, Docker で仮想 OS を起動するために要する時間は, VM に比べて圧倒的に早い. また, パッケージ化された環境 (=イメージ) のサイズも完全な OS に比べ圧倒的に小さくなるので,ネットワークを通じたやり取りが非常に高速化される点も重要である 加えて, VM のいくつかの実装では,メタル (仮想化マシンに対して,物理的なハードウェア上で直接起動する場合のこと) と比べ,ハイパーバイザーレイヤーでのオーバーヘッドなどにより性能が低下することが知られているが, Docker ではメタルとほぼ同様の性能を引き出すことができるとされている.

その他, VM との相違点などはたくさんあるのだが,ここではこれ以上詳細には立ち入らない. 大事なのは, Docker とはとてもコンパクトかつハイパフォーマンスな仮想計算環境を作るツールである,という点である. その手軽さゆえに,2013 年の登場以降,クラウドシステムでの利用が急速に増加し,現代のクラウドでは欠くことのできない中心的な技術になっている.

Docker (左) と VM (右) の比較 (画像出典: https://www.docker.com/blog/containers-replacing-virtual-machines/)

職業的プログラマーにとっての"三種の神器"とはなんだろうか? 多様な意見があると思うが,筆者は Git, Vim そして Docker を挙げたい.

Git は多くの読者がご存じの通り,コードの変更を追跡するためのシステムである. Linux の作成者である Linus Torvalds によって 2005 年に誕生した. チームでの開発を進める際には欠かせないツールだ.

Vim は 1991 年から 30 年以上の間プログラマーたちに愛されてきたテキストエディターである. Stackoverflow が行った 2019 年のアンケート によると,開発環境の部門で 5 位の人気を獲得している. たくさんのショートカットと様々なカスタム設定が提供されているので,初見の人にはなかなかハードルが高いが,一度マスターすれば他のモダンなエディターや統合開発環境に負けない,あるいはそれ以上の開発体験を実現することができる.

これらの十年以上の歴史あるツールに並んで,第三番目の三種の神器として挙げたいのが Docker だ. Docker はプログラマーの開発のワークフローを一変させた. たとえば,プロジェクトごとに Docker イメージを作成することで,どの OS・コンピュータ でも全く同じ計算環境で開発・テストを実行することができるようになった. また, DevOpsCI / CD (Continuous Integration / Continuous Deployment) といった最近の開発ワークフローも Docker のようなコンテナ技術の存在に立脚している. さらにはサーバーレスコンピューティング ( (#sec_serverless)) といった概念も,コンテナ技術の生んだ大きな技術革新といえる.

あなたにとっての三種の神器はなんだろうか? また,これからの未来ではどんな新しいツールが三種の神器としてプログラマーのワークフローを革新していくだろうか?

Docker チュートリアル

Docker とはなにかを理解するためには,実際に触って動かしてみるのが一番有効な手立てである. ここでは, Docker の簡単なチュートリアルを行っていく.

Docker のインストールについては, (#sec:install_docker) および 公式のドキュメンテーション を参照してもらいたい. Docker のインストールが完了している前提で,以下は話を進めるものとする.

Docker 用語集

Docker を使い始めるに当たり,最初に主要な用語を解説しよう. 次のパラグラフで太字で強調された用語を頭に入れた上で,続くチュートリアルに取り組んでいただきたい.

Docker を起動する際の大まかなステップを示したのが figure_title である. パッケージされた一つの計算環境のことを **イメージ (Image)**とよぶ. イメージは, Docker Hub などのリポジトリで配布されているものをダウンロードするか,自分でカスタムのイメージを作成することも可能である. イメージを作成するための”レシピ”を記述したファイルが Dockerfile である. Dockerfile からイメージを作成する操作を build とよぶ. イメージがホストマシンのメモリにロードされ,起動状態にある計算環境のことを コンテナ (Container) とよぶ. Container を起動するために使用されるコマンドが run である.

Image と Container

イメージをダウンロード

パッケージ化された Docker の仮想環境 (= イメージ (Image)) は, Docker Hub からダウンロードできる. Docker Hub には,個人や企業・団体が作成した Docker イメージが集められており, GitHub などと同じ感覚で,オープンな形で公開されている.

たとえば, Ubuntu のイメージは Ubuntu の公式リポジトリ で公開されており, pull コマンドを使うことでローカルにダウンロードすることができる.

sh
$ docker pull ubuntu:18.04
$ docker pull ubuntu:18.04

ここで,イメージ名の : (コロン) 以降に続く文字列を タグ (tag) と呼び,主にバージョンを指定するなどの目的で使われる.

pull コマンドはデフォルトでは Docker Hub でイメージを検索し,ダウンロードを行う. Docker イメージを公開するためのデータベース (レジストリ (registry) とよぶ) は Docker Hub だけではなく,たとえば GitLab や GitHub は独自のレジストリ機能を提供しているし,個人のサーバーでレジストリを立ち上げることも可能である. Docker Hub 以外のレジストリから pull するには, myregistry.local:5000/testing/test-image のように,イメージ名の先頭につける形でレジストリのアドレス (さらにオプションとしてポート番号) を指定する.

コンテナを起動

Pull してきたイメージを起動するには, run コマンドを使う.

sh
$ docker run -it ubuntu:18.04
$ docker run -it ubuntu:18.04

ここで, -it とは,インタラクティブな shell のセッションを開始するために必要なオプションである.

このコマンドを実行すると,仮想化された Ubuntu が起動され,コマンドラインからコマンドが打ち込めるようになる (figure_title). このように起動状態にある計算環境 (ランタイム) のことを Container (コンテナ) とよぶ.

Docker を使って ubuntu:18.04 イメージを起動

ここで使用した ubuntu:18.04 のイメージは,空の Ubuntu OS だが,すでにプログラムがインストール済みのものもある. これは, (#sec_jupyter_and_deep_learning) でみた DLAMI と概念として似ている. たとえば, PyTorch がインストール済みのイメージは PyTorch 公式の Docker Hub リポジトリ で公開されている.

これを起動してみよう.

sh
$ docker run -it pytorch/pytorch
$ docker run -it pytorch/pytorch

docker run を実行したとき,ローカルに該当するイメージが見つからない場合は,自動的に Docker Hub からダウンロードされる.

pytorch のコンテナが起動したら, Python のシェルを立ち上げて, pytorch をインポートしてみよう.

sh
$ python3
Python 3.7.7 (default, May  7 2020, 21:25:33)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.cuda.is_available()
False
$ python3
Python 3.7.7 (default, May  7 2020, 21:25:33)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.cuda.is_available()
False

このように, Docker を使うことで簡単に特定の OS・プログラムの入った計算環境を再現することが可能になる.

自分だけのイメージを作る

自分の使うソフトウェア・ライブラリがインストールされた,自分だけのイメージを作ることも可能である.

たとえば, 本書のハンズオン実行用に提供している docker イメージ には, Python, Node.js, AWS CLI, AWS CDK などのソフトウェアがインストール済みであり,ダウンロードしてくるだけですぐにハンズオンのプログラムが実行できるようになっている.

カスタムの docker イメージを作るには, Dockerfile という名前のついたファイルを用意し,その中にどんなプログラムをインストールするかなどを記述していく.

具体例として,本書で提供している Docker イメージのレシピを見てみよう (docker/Dockerfile).

dockerfile
FROM node:12
LABEL maintainer="Tomoyuki Mano"

RUN apt-get update \
    && apt-get install nano

#
RUN cd /opt \
    && curl -q "https://www.python.org/ftp/python/3.7.6/Python-3.7.6.tgz" -o Python-3.7.6.tgz \
    && tar -xzf Python-3.7.6.tgz \
    && cd Python-3.7.6 \
    && ./configure --enable-optimizations \
    && make install

RUN cd /opt \
    && curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" \
    && unzip awscliv2.zip \
    && ./aws/install

#
RUN npm install -g aws-cdk@1.100

# clean up unnecessary files
RUN rm -rf /opt/*

# copy hands-on source code in /root/
COPY handson/ /root/handson
FROM node:12
LABEL maintainer="Tomoyuki Mano"

RUN apt-get update \
    && apt-get install nano

#
RUN cd /opt \
    && curl -q "https://www.python.org/ftp/python/3.7.6/Python-3.7.6.tgz" -o Python-3.7.6.tgz \
    && tar -xzf Python-3.7.6.tgz \
    && cd Python-3.7.6 \
    && ./configure --enable-optimizations \
    && make install

RUN cd /opt \
    && curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" \
    && unzip awscliv2.zip \
    && ./aws/install

#
RUN npm install -g aws-cdk@1.100

# clean up unnecessary files
RUN rm -rf /opt/*

# copy hands-on source code in /root/
COPY handson/ /root/handson

Dockerfile の中身の説明は詳しくは行わないが,たとえば上のコードで <1> で示したところは, Python 3.7 のインストールを実行している. また, <2> で示したところは, AWS CDK のインストールを行っていることがわかるだろう. このように,リアルな OS で行うのと同じ流れでインストールのコマンドを逐一記述していくことで,自分だけの Docker イメージを作成することができる. 一度イメージを作成すれば,それを配布することで,他者も同一の計算環境を簡単に再構成することができる.

"ぼくの環境ではそのプログラム走ったのにな…" というのは,プログラミング初心者ではよく耳にする会話だが, Docker を使いこなせばそのような心配とは無縁である. そのような意味で,クラウド以外の場面でも, Docker の有用性・汎用性は極めて高い.

コンテナを用いた仮想計算環境ツールとして Docker を紹介したが, ほかに選択肢はないのか? よくぞ聞いてくれた! Docker の登場以降,複数のコンテナベースの仮想環境ツールが開発されてきた. いずれのツールも,概念や API については Docker と共通するものが多いが,Docker にはない独自の特徴を提供している. ここではその中でも有名ないくつかを紹介しよう.

Singularity は科学計算や HPC (High Performance Computing) の分野で人気の高いコンテナプラットフォームである. Singularity では大学・研究機関の HPC クラスターでの運用に適したような設計が施されている. たとえば, Docker は基本的には root 権限で実行されるのに対し, Singularity はユーザー権限 (コマンドを実行したユーザー自身) でプログラムが実行される. root 権限での実行は Web サーバーのように個人・企業がある特定のサービスのために運用するサーバーでは問題ないが,多数のユーザーが多様な目的で計算を実行する HPC クラスターでは問題となる. また,Singularity は独自のイメージの作成方法・エコシステムをもっているが, Docker イメージを Singularity のイメージに変換し実行する機能も有している.

podman は Red Hat 社によって開発されたもう一つのコンテナプラットフォームである. podman は基本的に Docker と同一のコマンドを採用しているが,実装は Red Hat によってスクラッチから行われた. podman では, Singularity と同様にユーザー権限でのプログラムの実行を可能であり,クラウドおよび HPC の両方の環境に対応するコンテナプラットフォームを目指して作られた. また,その名前にあるとおり pod とよばれる独自の概念が導入されている.

著者の個人的な意見としては,現時点では Docker をマスターしておけば当面は困ることはないと考えるが,興味のある読者はぜひこれらのツールも試してみてはいかがだろうか?

Elastic Container Service (ECS)

ECS のアイコン

ここまでに説明してきたように, Docker を使うことで仮想計算環境を簡単に複製・起動することが可能になる. 本章の最後の話題として, AWS 上で Docker を使った計算システムを構築する方法を解説しよう.

Elastic Container Service (ECS) とは, Docker を使った計算機クラスターを AWS 上に作成するためのツールである (figure_title). ECS を使用することで, Docker にパッケージされたアプリケーションを計算機クラスターに投入したり,計算機クラスターのインスタンスを追加・削除する操作 (=スケーリング) を行うことができる.

ECS の概要を示したのが figure_title である. ECS は,タスク (Task) と呼ばれる単位で管理された計算ジョブを受け付ける. システムにタスクが投入されると,ECS は最初にタスクで指定された Docker イメージを外部レジストリからダウンロードしてくる. 外部レジストリとしては, Docker Hub や AWS 独自の Docker レジストリである ECR (Elastic Container Registry) を指定することができる.

ECS の次の重要な役割はタスクの配置である. あらかじめ定義されたクラスター内で,計算負荷が小さい仮想インスタンスを選び出し,そこに Docker イメージを配置することで指定された計算タスクが開始される. "計算負荷が小さい仮想インスタンスを選び出す" と言ったが,具体的にどのような戦略・ポリシーでこの選択を行うかは,ユーザーの指定したパラメータに従う.

また,クラスターのスケーリングも ECS における重要な概念である. スケーリングとは,クラスター内のインスタンスの計算負荷をモニタリングし,計算負荷に応じてインスタンスの起動・停止を行う操作を指す. クラスター全体の計算負荷が指定された閾値 (たとえば 80%の稼働率) を超えていた場合,新たな仮想インスタンスをクラスター内に立ち上げる操作を scale-out (スケールアウト) とよび, 負荷が減った場合に不要なインスタンスを停止する操作を scale-in (スケールイン) とよぶ. クラスターのスケーリングは, ECS がほかの AWS のサービスと連携することで実現される. 具体的には, EC2 の Auto scaling group (ASG)Fargate の2つの選択肢が多くの場合選択される. ASG については (#sec_aws_batch), Fargate については (#sec_fargate_qabot) でより詳細に解説する.

これら一連のタスクの管理を, ECS は自動でやってくれる. クラスターのスケーリングやタスクの配置に関してのパラメータを一度指定してしまえば,ユーザーは (ほとんどなにも考えずに) 大量のタスクを投入することができる. クラスターのスケーリングによってタスクの量にちょうど十分なだけのインスタンスが起動し,タスクが完了した後は不要なインスタンスはすべて停止される.

さて,ここまで説明的な話が続いてしまったが,次章からは早速 Docker と AWS を使って大規模な並列計算システムを構築していこう!

ECS の概要

]]>
Docker 入門

ここまでの章で扱ってきたハンズオンでは,単一のサーバーを立ち上げ,それに SSH でログインをして,コマンドを叩くことで計算を行ってきた. いわば,パーソナルコンピュータの延長のような形でクラウドを使ってきたわけである. このような,インターネットのどこからでもアクセスできるパーソナルコンピュータとしてのクラウドという使い方も,もちろん便利であるし,いろいろな応用の可能性がある. しかし,これだけではクラウドの本当の価値は十分に発揮されていないと言うべきだろう. (#chap_cloud_basics) で述べたように,現代的なクラウドの一番の強みは自由に計算機の規模を拡大できることにある. すなわち,多数のサーバーを同時に起動し,複数のジョブを分散並列的に実行させることで大量のデータを処理してこそ,クラウドの本領が発揮されるのである.

本章からはじまる 3 章分 (Docker 入門, (#sec_fargate_qabot), (#sec_aws_batch)) を使って,クラウドを利用することでどのように大規模な計算システムを構築しビッグデータの解析に立ち向かうのか,その片鱗をお見せしたい. とくに,前章で扱った深層学習をどのようにビッグデータに適用していくかという点に焦点を絞って議論していきたい. そのための前準備として,本章では Docker とよばれる計算機環境の仮想化ソフトウェアを紹介する (figure_title). 現代のクラウドは Docker なしには成り立たないといっても過言ではないだろう. クラウドに限らず,ローカルで行う計算処理にも Docker は大変便利である. AWS からは少し話が離れるが,しっかりと理解して前に進んでもらいたい.

機械学習の大規模化

先ほどから"計算システムの大規模化"と繰り返し唱えているが,それは具体的にはどのようなものを指しているのか? ここでは大規模データを処理するための計算機システムを,機械学習を例にとって見てみよう.

(#sec_scientific_computing) で紹介した GPT-3 のような,超巨大な数のパラメータを有する深層学習モデルを学習させたいとしよう. そのような計算を行いたい場合,一つのサーバーでは計算力が到底足りない. したがって,典型的には figure_title に示すような計算システムの設計がなされる. すなわち,大量の教師データを小さなチャンクとして複数のマシンに分散し,並列的にニューラルネットのパラメータを最適化していくという構造である.

複数の計算機を使った大規模な深層学習モデルの訓練

あるいは,学習済みのモデルを大量のデータに適用し,解析を行いたいとしよう. たとえば, SNS のプラットフォームで大量の画像が与えられて,それぞれの写真に何が写っているのかをラベルづけする,などのアプリケーションを想定できる. そのような場合は, figure_title のようなアーキテクチャが考えられるだろう. すなわち,大量のデータを複数のマシンで分割し,それぞれのマシンで推論の計算を行うというような構造である.

複数の計算機による深層学習モデルを使った推論計算

このような複数の計算機を同時に走らせるようなアプリケーションをクラウド上で実現するには,どのようにすればよいのだろうか?

重要なポイントとして, figure_titlefigure_title で起動している複数のマシンは,基本的に全く同一の OS・計算環境を有している点である. ここで,個人のコンピュータで行うようなインストールの操作を,各マシンで行うこともできるが,それは大変な手間であるし,メンテナンスも面倒だろう. すなわち,大規模な計算システムを構築するには,簡単に計算環境を複製できるような仕組みが必要であるということがわかる.

そのような目的を実現するために使われるのが, Docker とよばれるソフトウェアである.

Docker とは

Docker のアイコン

Docker とは, コンテナ (Container) とよばれる仮想環境下で,ホスト OS とは独立した別の計算環境を走らせるためのソフトウェアである. Docker を使うことで, OS を含めたすべてのプログラムをコンパクトにパッケージングすることが可能になる (パッケージされた一つの計算環境のことを **イメージ (Image)**とよぶ). Docker を使うことで,クラウドのサーバー上に瞬時に計算環境を複製することが可能になり, figure_title で見たような複数の計算機を同時に走らせるためのシステムが実現できる.

Docker は 2013 年に Solomon Hykes らを中心に開発され,それ以降爆発的に普及し,クラウドコンピューティングだけでなく,機械学習・科学計算の文脈などでも欠かすことのできないソフトウェアとなった. Docker はエンタープライズ向けの製品を除き無料で使用することができ,コアの部分は オープンソースプロジェクト として公開されている. Docker は Linux, Windows, Mac いずれの OS でも提供されている. 概念としては, Docker は仮想マシン (Virtual machine; VM) にとても近い. ここでは, VM との対比をしながら,Docker とはなにかを簡単に説明しよう.

仮想マシン (VM) とは,ホストとなるマシンの上に,仮想化された OS を走らせる技術である (figure_title). VM には ハイパーバイザー (Hypervisor) とよばれるレイヤーが存在する. Hypervisor はまず,物理的な計算機リソース (CPU, RAM, network など) を分割し,仮想化する. たとえば, ホストマシンに物理的な CPU が 4 コアあるとして,ハイパーバイザーはそれを (2,2) 個の組に仮想的に分割することができる. VM 上で起動する OS には,ハイパーバイザーによって仮想化されたハードウェアが割り当てられる. VM 上で起動する OS は基本的に完全に独立であり,たとえば OS-A は OS-B に割り当てられた CPU やメモリー領域にアクセスすることはできない (これを isolation とよぶ). VM を作成するための有名なソフトウェアとしては, VMwareVirtualBoxXen などがある. また,これまで触ってきた EC2 も,基本的に VM 技術を使うことで所望のスペックをもった仮想マシンがユーザーに提示される.

Docker も, VM と同様に,仮想化された OS をホストの OS 上に走らせるための技術である. VM に対し, Docker ではハードウェアレベルの仮想化は行われておらず,すべての仮想化はソフトウェアレベルで実現されている (figure_title). Docker で走る仮想 OS は,多くの部分をホストの OS に依存しており,結果として非常にコンパクトである. その結果, Docker で仮想 OS を起動するために要する時間は, VM に比べて圧倒的に早い. また, パッケージ化された環境 (=イメージ) のサイズも完全な OS に比べ圧倒的に小さくなるので,ネットワークを通じたやり取りが非常に高速化される点も重要である 加えて, VM のいくつかの実装では,メタル (仮想化マシンに対して,物理的なハードウェア上で直接起動する場合のこと) と比べ,ハイパーバイザーレイヤーでのオーバーヘッドなどにより性能が低下することが知られているが, Docker ではメタルとほぼ同様の性能を引き出すことができるとされている.

その他, VM との相違点などはたくさんあるのだが,ここではこれ以上詳細には立ち入らない. 大事なのは, Docker とはとてもコンパクトかつハイパフォーマンスな仮想計算環境を作るツールである,という点である. その手軽さゆえに,2013 年の登場以降,クラウドシステムでの利用が急速に増加し,現代のクラウドでは欠くことのできない中心的な技術になっている.

Docker (左) と VM (右) の比較 (画像出典: https://www.docker.com/blog/containers-replacing-virtual-machines/)

職業的プログラマーにとっての"三種の神器"とはなんだろうか? 多様な意見があると思うが,筆者は Git, Vim そして Docker を挙げたい.

Git は多くの読者がご存じの通り,コードの変更を追跡するためのシステムである. Linux の作成者である Linus Torvalds によって 2005 年に誕生した. チームでの開発を進める際には欠かせないツールだ.

Vim は 1991 年から 30 年以上の間プログラマーたちに愛されてきたテキストエディターである. Stackoverflow が行った 2019 年のアンケート によると,開発環境の部門で 5 位の人気を獲得している. たくさんのショートカットと様々なカスタム設定が提供されているので,初見の人にはなかなかハードルが高いが,一度マスターすれば他のモダンなエディターや統合開発環境に負けない,あるいはそれ以上の開発体験を実現することができる.

これらの十年以上の歴史あるツールに並んで,第三番目の三種の神器として挙げたいのが Docker だ. Docker はプログラマーの開発のワークフローを一変させた. たとえば,プロジェクトごとに Docker イメージを作成することで,どの OS・コンピュータ でも全く同じ計算環境で開発・テストを実行することができるようになった. また, DevOpsCI / CD (Continuous Integration / Continuous Deployment) といった最近の開発ワークフローも Docker のようなコンテナ技術の存在に立脚している. さらにはサーバーレスコンピューティング ( (#sec_serverless)) といった概念も,コンテナ技術の生んだ大きな技術革新といえる.

あなたにとっての三種の神器はなんだろうか? また,これからの未来ではどんな新しいツールが三種の神器としてプログラマーのワークフローを革新していくだろうか?

Docker チュートリアル

Docker とはなにかを理解するためには,実際に触って動かしてみるのが一番有効な手立てである. ここでは, Docker の簡単なチュートリアルを行っていく.

Docker のインストールについては, (#sec:install_docker) および 公式のドキュメンテーション を参照してもらいたい. Docker のインストールが完了している前提で,以下は話を進めるものとする.

Docker 用語集

Docker を使い始めるに当たり,最初に主要な用語を解説しよう. 次のパラグラフで太字で強調された用語を頭に入れた上で,続くチュートリアルに取り組んでいただきたい.

Docker を起動する際の大まかなステップを示したのが figure_title である. パッケージされた一つの計算環境のことを **イメージ (Image)**とよぶ. イメージは, Docker Hub などのリポジトリで配布されているものをダウンロードするか,自分でカスタムのイメージを作成することも可能である. イメージを作成するための”レシピ”を記述したファイルが Dockerfile である. Dockerfile からイメージを作成する操作を build とよぶ. イメージがホストマシンのメモリにロードされ,起動状態にある計算環境のことを コンテナ (Container) とよぶ. Container を起動するために使用されるコマンドが run である.

Image と Container

イメージをダウンロード

パッケージ化された Docker の仮想環境 (= イメージ (Image)) は, Docker Hub からダウンロードできる. Docker Hub には,個人や企業・団体が作成した Docker イメージが集められており, GitHub などと同じ感覚で,オープンな形で公開されている.

たとえば, Ubuntu のイメージは Ubuntu の公式リポジトリ で公開されており, pull コマンドを使うことでローカルにダウンロードすることができる.

sh
$ docker pull ubuntu:18.04
$ docker pull ubuntu:18.04

ここで,イメージ名の : (コロン) 以降に続く文字列を タグ (tag) と呼び,主にバージョンを指定するなどの目的で使われる.

pull コマンドはデフォルトでは Docker Hub でイメージを検索し,ダウンロードを行う. Docker イメージを公開するためのデータベース (レジストリ (registry) とよぶ) は Docker Hub だけではなく,たとえば GitLab や GitHub は独自のレジストリ機能を提供しているし,個人のサーバーでレジストリを立ち上げることも可能である. Docker Hub 以外のレジストリから pull するには, myregistry.local:5000/testing/test-image のように,イメージ名の先頭につける形でレジストリのアドレス (さらにオプションとしてポート番号) を指定する.

コンテナを起動

Pull してきたイメージを起動するには, run コマンドを使う.

sh
$ docker run -it ubuntu:18.04
$ docker run -it ubuntu:18.04

ここで, -it とは,インタラクティブな shell のセッションを開始するために必要なオプションである.

このコマンドを実行すると,仮想化された Ubuntu が起動され,コマンドラインからコマンドが打ち込めるようになる (figure_title). このように起動状態にある計算環境 (ランタイム) のことを Container (コンテナ) とよぶ.

Docker を使って ubuntu:18.04 イメージを起動

ここで使用した ubuntu:18.04 のイメージは,空の Ubuntu OS だが,すでにプログラムがインストール済みのものもある. これは, (#sec_jupyter_and_deep_learning) でみた DLAMI と概念として似ている. たとえば, PyTorch がインストール済みのイメージは PyTorch 公式の Docker Hub リポジトリ で公開されている.

これを起動してみよう.

sh
$ docker run -it pytorch/pytorch
$ docker run -it pytorch/pytorch

docker run を実行したとき,ローカルに該当するイメージが見つからない場合は,自動的に Docker Hub からダウンロードされる.

pytorch のコンテナが起動したら, Python のシェルを立ち上げて, pytorch をインポートしてみよう.

sh
$ python3
Python 3.7.7 (default, May  7 2020, 21:25:33)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.cuda.is_available()
False
$ python3
Python 3.7.7 (default, May  7 2020, 21:25:33)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.cuda.is_available()
False

このように, Docker を使うことで簡単に特定の OS・プログラムの入った計算環境を再現することが可能になる.

自分だけのイメージを作る

自分の使うソフトウェア・ライブラリがインストールされた,自分だけのイメージを作ることも可能である.

たとえば, 本書のハンズオン実行用に提供している docker イメージ には, Python, Node.js, AWS CLI, AWS CDK などのソフトウェアがインストール済みであり,ダウンロードしてくるだけですぐにハンズオンのプログラムが実行できるようになっている.

カスタムの docker イメージを作るには, Dockerfile という名前のついたファイルを用意し,その中にどんなプログラムをインストールするかなどを記述していく.

具体例として,本書で提供している Docker イメージのレシピを見てみよう (docker/Dockerfile).

dockerfile
FROM node:12
LABEL maintainer="Tomoyuki Mano"

RUN apt-get update \
    && apt-get install nano

#
RUN cd /opt \
    && curl -q "https://www.python.org/ftp/python/3.7.6/Python-3.7.6.tgz" -o Python-3.7.6.tgz \
    && tar -xzf Python-3.7.6.tgz \
    && cd Python-3.7.6 \
    && ./configure --enable-optimizations \
    && make install

RUN cd /opt \
    && curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" \
    && unzip awscliv2.zip \
    && ./aws/install

#
RUN npm install -g aws-cdk@1.100

# clean up unnecessary files
RUN rm -rf /opt/*

# copy hands-on source code in /root/
COPY handson/ /root/handson
FROM node:12
LABEL maintainer="Tomoyuki Mano"

RUN apt-get update \
    && apt-get install nano

#
RUN cd /opt \
    && curl -q "https://www.python.org/ftp/python/3.7.6/Python-3.7.6.tgz" -o Python-3.7.6.tgz \
    && tar -xzf Python-3.7.6.tgz \
    && cd Python-3.7.6 \
    && ./configure --enable-optimizations \
    && make install

RUN cd /opt \
    && curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" \
    && unzip awscliv2.zip \
    && ./aws/install

#
RUN npm install -g aws-cdk@1.100

# clean up unnecessary files
RUN rm -rf /opt/*

# copy hands-on source code in /root/
COPY handson/ /root/handson

Dockerfile の中身の説明は詳しくは行わないが,たとえば上のコードで <1> で示したところは, Python 3.7 のインストールを実行している. また, <2> で示したところは, AWS CDK のインストールを行っていることがわかるだろう. このように,リアルな OS で行うのと同じ流れでインストールのコマンドを逐一記述していくことで,自分だけの Docker イメージを作成することができる. 一度イメージを作成すれば,それを配布することで,他者も同一の計算環境を簡単に再構成することができる.

"ぼくの環境ではそのプログラム走ったのにな…" というのは,プログラミング初心者ではよく耳にする会話だが, Docker を使いこなせばそのような心配とは無縁である. そのような意味で,クラウド以外の場面でも, Docker の有用性・汎用性は極めて高い.

コンテナを用いた仮想計算環境ツールとして Docker を紹介したが, ほかに選択肢はないのか? よくぞ聞いてくれた! Docker の登場以降,複数のコンテナベースの仮想環境ツールが開発されてきた. いずれのツールも,概念や API については Docker と共通するものが多いが,Docker にはない独自の特徴を提供している. ここではその中でも有名ないくつかを紹介しよう.

Singularity は科学計算や HPC (High Performance Computing) の分野で人気の高いコンテナプラットフォームである. Singularity では大学・研究機関の HPC クラスターでの運用に適したような設計が施されている. たとえば, Docker は基本的には root 権限で実行されるのに対し, Singularity はユーザー権限 (コマンドを実行したユーザー自身) でプログラムが実行される. root 権限での実行は Web サーバーのように個人・企業がある特定のサービスのために運用するサーバーでは問題ないが,多数のユーザーが多様な目的で計算を実行する HPC クラスターでは問題となる. また,Singularity は独自のイメージの作成方法・エコシステムをもっているが, Docker イメージを Singularity のイメージに変換し実行する機能も有している.

podman は Red Hat 社によって開発されたもう一つのコンテナプラットフォームである. podman は基本的に Docker と同一のコマンドを採用しているが,実装は Red Hat によってスクラッチから行われた. podman では, Singularity と同様にユーザー権限でのプログラムの実行を可能であり,クラウドおよび HPC の両方の環境に対応するコンテナプラットフォームを目指して作られた. また,その名前にあるとおり pod とよばれる独自の概念が導入されている.

著者の個人的な意見としては,現時点では Docker をマスターしておけば当面は困ることはないと考えるが,興味のある読者はぜひこれらのツールも試してみてはいかがだろうか?

Elastic Container Service (ECS)

ECS のアイコン

ここまでに説明してきたように, Docker を使うことで仮想計算環境を簡単に複製・起動することが可能になる. 本章の最後の話題として, AWS 上で Docker を使った計算システムを構築する方法を解説しよう.

Elastic Container Service (ECS) とは, Docker を使った計算機クラスターを AWS 上に作成するためのツールである (figure_title). ECS を使用することで, Docker にパッケージされたアプリケーションを計算機クラスターに投入したり,計算機クラスターのインスタンスを追加・削除する操作 (=スケーリング) を行うことができる.

ECS の概要を示したのが figure_title である. ECS は,タスク (Task) と呼ばれる単位で管理された計算ジョブを受け付ける. システムにタスクが投入されると,ECS は最初にタスクで指定された Docker イメージを外部レジストリからダウンロードしてくる. 外部レジストリとしては, Docker Hub や AWS 独自の Docker レジストリである ECR (Elastic Container Registry) を指定することができる.

ECS の次の重要な役割はタスクの配置である. あらかじめ定義されたクラスター内で,計算負荷が小さい仮想インスタンスを選び出し,そこに Docker イメージを配置することで指定された計算タスクが開始される. "計算負荷が小さい仮想インスタンスを選び出す" と言ったが,具体的にどのような戦略・ポリシーでこの選択を行うかは,ユーザーの指定したパラメータに従う.

また,クラスターのスケーリングも ECS における重要な概念である. スケーリングとは,クラスター内のインスタンスの計算負荷をモニタリングし,計算負荷に応じてインスタンスの起動・停止を行う操作を指す. クラスター全体の計算負荷が指定された閾値 (たとえば 80%の稼働率) を超えていた場合,新たな仮想インスタンスをクラスター内に立ち上げる操作を scale-out (スケールアウト) とよび, 負荷が減った場合に不要なインスタンスを停止する操作を scale-in (スケールイン) とよぶ. クラスターのスケーリングは, ECS がほかの AWS のサービスと連携することで実現される. 具体的には, EC2 の Auto scaling group (ASG)Fargate の2つの選択肢が多くの場合選択される. ASG については (#sec_aws_batch), Fargate については (#sec_fargate_qabot) でより詳細に解説する.

これら一連のタスクの管理を, ECS は自動でやってくれる. クラスターのスケーリングやタスクの配置に関してのパラメータを一度指定してしまえば,ユーザーは (ほとんどなにも考えずに) 大量のタスクを投入することができる. クラスターのスケーリングによってタスクの量にちょうど十分なだけのインスタンスが起動し,タスクが完了した後は不要なインスタンスはすべて停止される.

さて,ここまで説明的な話が続いてしまったが,次章からは早速 Docker と AWS を使って大規模な並列計算システムを構築していこう!

ECS の概要

]]>
<![CDATA[Hands-on #6: Bashoutter ]]> https://note.toshiki.dev/development/aws/handson-bashoutter https://note.toshiki.dev/development/aws/handson-bashoutter Thu, 01 Jul 2021 00:00:00 GMT Hands-on #6: Bashoutter

さて,最後のハンズオンとなる第六回では,これまで学んできたサーバーレスクラウドの技術を使って,簡単なウェブサービスを作ってみよう. 具体的には,人々が自分の作った俳句を投稿する SNS サービス (Bashoutter と名付ける) を作成してみよう. Lambda, DynamoDB, S3 などの技術をすべて盛り込み,シンプルながらもサーバーレスの利点を生かしたスケーラブルな SNS アプリが誕生する. 最終的には, figure_title のような,ミニマルではあるがとても現代風な SNS サイトが完成する!

ハンズオン#6で作製する SNS アプリケーション "Bashoutter"

準備

ハンズオンのソースコードは GitHub の handson/bashoutter に置いてある.

本ハンズオンの実行には,第一回ハンズオンで説明した準備 ( (#handson_01_prep)) が整っていることを前提とする. それ以外に必要な準備はない.

このハンズオンは,基本的に AWS の無料枠 の範囲内で実行できる.

アプリケーションの説明

API

今回のアプリケーションでは,人々からの俳句の投稿を受け付けたり,投稿された俳句の一覧を取得する,といった機能を実装したい. この機能を実現するための最小限の設計として, table_title に示すような四つの REST API を今回は実装する. 俳句を投稿する,閲覧する,削除するという基本的なデータ操作を行うための API が完備されている. また, PATCH /haiku/{item_id} は, {item_id} で指定された俳句に”いいね”をするために使用する.

Bashoutter API

GET /haiku

俳句の一覧を取得する

POST /haiku

新しい俳句を投稿する

PATCH /haiku/{item_id}

{item_id} で指定された俳句にお気に入り票を一つ入れる

DELETE /haiku/{item_id}

{item_id} で指定された俳句を削除する

それぞれの API のパラメータおよび返り値の詳細は,ハンズオンのソースコードの中の swagger.yml に定義してある.

Open API Specification (OAS; 少し前は Swagger Specification とよばれていた) は, REST API のための記述フォーマットである. OAS に従って API の仕様が記述されていると,簡単にドキュメンテーションを生成したり,クライアントアプリケーションを自動生成することができる. 今回用意した API 仕様 も, OAS に従って書いてある. 詳しくは Swagger の公式ドキュメンテーション などを参照.

アプリケーションアーキテクチャ

このハンズオンで作成するアプリケーションの概要を figure_title に示す.

ハンズオン#5で作製するアプリケーションのアーキテクチャ

簡単にまとめると,次のような設計である.

  • クライアントからの API リクエストは, API Gateway (後述)にまず送信され, API の URI で指定された Lambda 関数へ転送される.

  • それぞれの API のパス (リソース) ごとに独立した Lambda を用意する.

  • 俳句の情報 (作者,本文,投稿日時など) を記録するためのデータベース (DynamoDB) を用意する.

  • 各 Lambda 関数には, DynamoDB へのアクセス権を付与する.

  • 最後に,ウェブブラウザからコンテンツを表示できるよう, ウェブページの静的コンテンツを配信するための S3 バケットを用意する.クライアントはこの S3 バケットにアクセスすることで HTML/CSS/JS などのコンテンツを取得する.

それでは,プログラムのソースコードを見てみよう (handson/bashoutter/app.py).

python
class Bashoutter(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        # dynamoDB table to store haiku
        table = ddb.Table(
            self, "Bashoutter-Table",
            partition_key=ddb.Attribute(
                name="item_id",
                type=ddb.AttributeType.STRING
            ),
            billing_mode=ddb.BillingMode.PAY_PER_REQUEST,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        #
        bucket = s3.Bucket(
            self, "Bashoutter-Bucket",
            website_index_document="index.html",
            public_read_access=True,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        common_params = {
            "runtime": _lambda.Runtime.PYTHON_3_7,
            "environment": {
                "TABLE_NAME": table.table_name
            }
        }

        #
        # define Lambda functions
        get_haiku_lambda = _lambda.Function(
            self, "GetHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.get_haiku",
            memory_size=512,
            **common_params,
        )
        post_haiku_lambda = _lambda.Function(
            self, "PostHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.post_haiku",
            **common_params,
        )
        patch_haiku_lambda = _lambda.Function(
            self, "PatchHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.patch_haiku",
            **common_params,
        )
        delete_haiku_lambda = _lambda.Function(
            self, "DeleteHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.delete_haiku",
            **common_params,
        )

        #
        # grant permissions
        table.grant_read_data(get_haiku_lambda)
        table.grant_read_write_data(post_haiku_lambda)
        table.grant_read_write_data(patch_haiku_lambda)
        table.grant_read_write_data(delete_haiku_lambda)

        #
        # define API Gateway
        api = apigw.RestApi(
            self, "BashoutterApi",
            default_cors_preflight_options=apigw.CorsOptions(
                allow_origins=apigw.Cors.ALL_ORIGINS,
                allow_methods=apigw.Cors.ALL_METHODS,
            )
        )

        haiku = api.root.add_resource("haiku")
        haiku.add_method(
            "GET",
            apigw.LambdaIntegration(get_haiku_lambda)
        )
        haiku.add_method(
            "POST",
            apigw.LambdaIntegration(post_haiku_lambda)
        )

        haiku_item_id = haiku.add_resource("{item_id}")
        haiku_item_id.add_method(
            "PATCH",
            apigw.LambdaIntegration(patch_haiku_lambda)
        )
        haiku_item_id.add_method(
            "DELETE",
            apigw.LambdaIntegration(delete_haiku_lambda)
        )
class Bashoutter(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        # dynamoDB table to store haiku
        table = ddb.Table(
            self, "Bashoutter-Table",
            partition_key=ddb.Attribute(
                name="item_id",
                type=ddb.AttributeType.STRING
            ),
            billing_mode=ddb.BillingMode.PAY_PER_REQUEST,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        #
        bucket = s3.Bucket(
            self, "Bashoutter-Bucket",
            website_index_document="index.html",
            public_read_access=True,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        common_params = {
            "runtime": _lambda.Runtime.PYTHON_3_7,
            "environment": {
                "TABLE_NAME": table.table_name
            }
        }

        #
        # define Lambda functions
        get_haiku_lambda = _lambda.Function(
            self, "GetHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.get_haiku",
            memory_size=512,
            **common_params,
        )
        post_haiku_lambda = _lambda.Function(
            self, "PostHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.post_haiku",
            **common_params,
        )
        patch_haiku_lambda = _lambda.Function(
            self, "PatchHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.patch_haiku",
            **common_params,
        )
        delete_haiku_lambda = _lambda.Function(
            self, "DeleteHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.delete_haiku",
            **common_params,
        )

        #
        # grant permissions
        table.grant_read_data(get_haiku_lambda)
        table.grant_read_write_data(post_haiku_lambda)
        table.grant_read_write_data(patch_haiku_lambda)
        table.grant_read_write_data(delete_haiku_lambda)

        #
        # define API Gateway
        api = apigw.RestApi(
            self, "BashoutterApi",
            default_cors_preflight_options=apigw.CorsOptions(
                allow_origins=apigw.Cors.ALL_ORIGINS,
                allow_methods=apigw.Cors.ALL_METHODS,
            )
        )

        haiku = api.root.add_resource("haiku")
        haiku.add_method(
            "GET",
            apigw.LambdaIntegration(get_haiku_lambda)
        )
        haiku.add_method(
            "POST",
            apigw.LambdaIntegration(post_haiku_lambda)
        )

        haiku_item_id = haiku.add_resource("{item_id}")
        haiku_item_id.add_method(
            "PATCH",
            apigw.LambdaIntegration(patch_haiku_lambda)
        )
        haiku_item_id.add_method(
            "DELETE",
            apigw.LambdaIntegration(delete_haiku_lambda)
        )
  • ここで,俳句の情報を記録しておくための DynamoDB テーブルを定義している.

  • 静的コンテンツを配信するための S3 バケットを用意している.

  • それぞれの API で実行される Lambda 関数を定義している. 関数は Python3.7 で書かれており,コードは handson/bashoutter/api/api.py にある.

  • <3> で定義された Lambda 関数に対し,データベースへの読み書きのアクセス権限を付与している.

  • ここで,API Gateway により,各 API パスとそこで実行されるべき Lambda 関数を紐付けている.

それぞれの項目について,もう少し詳しく説明しよう.

Public access mode の S3 バケット

S3 のバケットを作成しているコードを見てみよう.

python
bucket = s3.Bucket(
    self, "Bashoutter-Bucket",
    website_index_document="index.html",
    public_read_access=True,
    removal_policy=core.RemovalPolicy.DESTROY
)
bucket = s3.Bucket(
    self, "Bashoutter-Bucket",
    website_index_document="index.html",
    public_read_access=True,
    removal_policy=core.RemovalPolicy.DESTROY
)

ここで注目してほしいのは public_read_access=True の部分だ. 前章で, S3 について説明を行ったときには触れなかったが, S3 には Public access mode という機能がある. Public access mode をオンにしておくと,バケットの中のファイルは認証なしで (i.e. インターネット上の誰でも) 閲覧できるようになる. この設定は,一般公開されているウェブサイトの静的なコンテンツを置いておくのに最適であり,多くのサーバーレスによるウェブサービスでこのような設計が行われる. public access mode を設定しておくと, http://XXXX.s3-website-ap-northeast-1.amazonaws.com/ のような固有の URL がバケットに対して付与される. そして,クライアントがこの URL にアクセスをすると,バケットの中にある index.html がクライアントに返され,ページがロードされる (どのファイルが返されるかは, website_index_document="index.html" の部分で設定している.)

なお,この時点ではバケットは空である. HTML/CSS/JS など静的コンテンツの配置は,デプロイを行った後ほどのステップで行う.

より本格的なウェブページを運用する際には, public access mode の S3 バケットに, CloudFront という機能を追加することが一般的である. CloudFront により, Content Delivery Nework (CDN) や暗号化された HTTPS 通信を設定することができる. CloudFront についての詳細は 公式ドキュメンテーション "What is Amazon CloudFront?" などを参照いただきたい.

今回のハンズオンでは説明の簡略化のため CloudFront の設定を行わなかったが,興味のある読者は次のリンクのプログラムが参考になるだろう.

今回の S3 バケットには, AWS によって付与されたランダムな URL がついている. これを. example.com のような自分のドメインでホストしたければ, AWS によって付与された URL を自分のドメインの DNS レコードに追加すればよい.

API のハンドラ関数

API リクエストが来たときに,リクエストされた処理を行う関数のことをハンドラ (handler) 関数とよぶ. GET /haiku の API に対してのハンドラ関数を Lambda で定義している部分を見てみよう.

python
get_haiku_lambda = _lambda.Function(
    self, "GetHaiku",
    code=_lambda.Code.from_asset("api"),
    handler="api.get_haiku",
    memory_size=512,
    **common_params
)
get_haiku_lambda = _lambda.Function(
    self, "GetHaiku",
    code=_lambda.Code.from_asset("api"),
    handler="api.get_haiku",
    memory_size=512,
    **common_params
)

簡単なところから見ていくと, memory_size=512 の箇所でメモリーの使用量を 512MB に指定している. また, code=_lambda.Code.from_asset("api") によって外部のディレクトリ (api/) を参照せよと指定しており, handler="api.get_haiku" のところで api.py というファイルの get_haiku() という関数をハンドラ関数として実行せよ,と定義している.

次に,ハンドラ関数として使用されている get_haiku() のコードを見てみよう (handson/bashoutter/api/api.py).

python
ddb = boto3.resource("dynamodb")
table = ddb.Table(os.environ["TABLE_NAME"])

def get_haiku(event, context):
    """
    handler for GET /haiku
    """
    try:
        response = table.scan()

        status_code = 200
        resp = response.get("Items")
    except Exception as e:
        status_code = 500
        resp = {"description": f"Internal server error. {str(e)}"}
    return {
        "statusCode": status_code,
        "headers": HEADERS,
        "body": json.dumps(resp, cls=DecimalEncoder)
    }
ddb = boto3.resource("dynamodb")
table = ddb.Table(os.environ["TABLE_NAME"])

def get_haiku(event, context):
    """
    handler for GET /haiku
    """
    try:
        response = table.scan()

        status_code = 200
        resp = response.get("Items")
    except Exception as e:
        status_code = 500
        resp = {"description": f"Internal server error. {str(e)}"}
    return {
        "statusCode": status_code,
        "headers": HEADERS,
        "body": json.dumps(resp, cls=DecimalEncoder)
    }

response = table.scan() で,俳句の格納された DynamoDB テーブルから,すべての要素を取り出している. もしなにもエラーが起きなければステータスコード 200 が返され,もしなにかエラーが起こればステータスコード 500 が返されるようになっている.

上記のような操作を,ほかの API についても繰り返すことで,すべての API のハンドラ関数が定義されている.

GET /haiku のハンドラ関数で, response = table.scan() という部分があるが,実はこれは最善の書き方ではない. DynamoDB の scan() メソッドは,最大で 1MB までのデータしか返さない. データベースのサイズが大きく, 1MB 以上のデータがある場合には,再帰的に scan() メソッドをよぶ必要がある. 詳しくは boto3 ドキュメンテーション を参照.

AWS における権限の管理 (IAM)

以下の部分のコードに注目してほしい.

python
table.grant_read_data(get_haiku_lambda)
table.grant_read_write_data(post_haiku_lambda)
table.grant_read_write_data(patch_haiku_lambda)
table.grant_read_write_data(delete_haiku_lambda)
table.grant_read_data(get_haiku_lambda)
table.grant_read_write_data(post_haiku_lambda)
table.grant_read_write_data(patch_haiku_lambda)
table.grant_read_write_data(delete_haiku_lambda)

これまでは説明の簡略化のためにあえて触れてこなかったが, AWS には IAM (Identity and Access Management) という重要な概念がある. IAM は基本的に,あるリソースがほかのリソースに対してどのような権限をもっているか,を規定するものである. Lambda は,デフォルトの状態ではほかのリソースにアクセスする権限をなにも有していない. したがって, Lambda 関数が DynamoDB のデータを読み書きするためには,それを許可するような IAM が Lambda 関数に付与されていなければならない.今回の S3 バケットには, AWS によって付与されたランダムな URL がついている. これを. example.com のような自分のドメインでホストしたければ, AWS によって付与された URL を自分のドメインの DNS レコードに追加すればよい.

CDK による dynamodb.Table オブジェクトには grant_read_write_data() という便利なメソッドが備わっており,アクセスを許可したい Lambda 関数を引数としてこのメソッドを呼ぶことで,データベースへの読み書きを許可する IAM を付与することができる. 同様に,CDK の s3.Bucket オブジェクトにも grant_read_write() というメソッドが備わっており,これによってバケットへの読み書きを許可することができる. このメソッドは,実は (#sec_aws_batch) で AWS Batch によるクラスターを構成した際に使用した. 興味のある読者は振り返ってコードを確認してみよう.

各リソースに付与する IAM は,必要最低限の権限を与えるにとどめるというのが基本方針である. これにより,セキュリティを向上させるだけでなく,意図していないプログラムからのデータベースへの読み書きを防止するという点で,バグを未然に防ぐことができる.

そのような理由により,このコードでは GET のハンドラー関数に対しては grant_read_data() によって, read 権限のみを付与している.

API Gateway

API Gateway とは, API の"入り口"として,API のリクエストパスに従って Lambda や EC2 などに接続を行うという機能を担う (figure_title). Lambda や EC2 によって行われた処理の結果は,再び API Gateway を経由してクライアントに返される. このように,クライアントとバックエンドサーバーの間に立ち, API のリソースパスに応じて接続先を振り分けるようなサーバーをルーター,あるいはリバースプロキシとよんだりする. 従来的には,ルーターにはそれ専用の仮想サーバーが置かれることが一般的であった. しかし, API Gateway はサーバーレスなルーターとして,固定されたサーバーを配置することなく, API のリクエストが来たときのみ起動し,API のルーティングを実行する. サーバーレスであることの当然の帰結として,アクセスの件数が増大したときにはそれにルーティングの処理能力を自動で増やす機能も備わっている.

API Gateway

API Gateway を配置することで,大量 (1 秒間に数千から数万件) の API リクエストに対応することのできるシステムを容易に構築することができる. API Gateway の料金は table_title のように設定されている. また,無料利用枠により,月ごとに 100 万件までのリクエストは 0 円で利用できる.

API Gateway の利用料金設定 (参照)
Number of Requests (per month)Price (per million)

First 333 million

$4.25

Next 667 million

$3.53

Next 19 billion

$3.00

Over 20 billion

$1.91

ソースコードの該当箇所を見てみよう.

python
#
api = apigw.RestApi(
    self, "BashoutterApi",
    default_cors_preflight_options=apigw.CorsOptions(
        allow_origins=apigw.Cors.ALL_ORIGINS,
        allow_methods=apigw.Cors.ALL_METHODS,
    )
)

#
haiku = api.root.add_resource("haiku")
#
haiku.add_method(
    "GET",
    apigw.LambdaIntegration(get_haiku_lambda)
)
haiku.add_method(
    "POST",
    apigw.LambdaIntegration(post_haiku_lambda)
)

#
haiku_item_id = haiku.add_resource("{item_id}")
#
haiku_item_id.add_method(
    "PATCH",
    apigw.LambdaIntegration(patch_haiku_lambda)
)
haiku_item_id.add_method(
    "DELETE",
    apigw.LambdaIntegration(delete_haiku_lambda)
)
#
api = apigw.RestApi(
    self, "BashoutterApi",
    default_cors_preflight_options=apigw.CorsOptions(
        allow_origins=apigw.Cors.ALL_ORIGINS,
        allow_methods=apigw.Cors.ALL_METHODS,
    )
)

#
haiku = api.root.add_resource("haiku")
#
haiku.add_method(
    "GET",
    apigw.LambdaIntegration(get_haiku_lambda)
)
haiku.add_method(
    "POST",
    apigw.LambdaIntegration(post_haiku_lambda)
)

#
haiku_item_id = haiku.add_resource("{item_id}")
#
haiku_item_id.add_method(
    "PATCH",
    apigw.LambdaIntegration(patch_haiku_lambda)
)
haiku_item_id.add_method(
    "DELETE",
    apigw.LambdaIntegration(delete_haiku_lambda)
)
  • 最初に, api = apigw.RestApi() により,空の API Gateway を作成している.

  • 次に, api.root.add_resource() のメソッドを呼ぶことで, /haiku という API パスを追加している.

  • 続いて, add_method() を呼ぶことで, GET, POST のメソッドを /haiku のパスに定義している.

  • さらに, haiku.add_resource("{item_id}") により, /haiku/{item_id} という API パスを追加している.

  • 最後に, add_method() を呼ぶことにより, PATCH, DELETE のメソッドを /haiku/{item_id} のパスに定義している.

このように, API Gateway の使い方は非常にシンプルで,逐次的に API パスとそこで実行されるメソッド・Lambda を記述していくだけでよい.

このプログラムで 新規 API を作成すると, ランダムな URL がその API のエンドポイントとして割り当てられる. これを. api.example.com のような自分のドメインでホストしたければ, AWS によって付与された URL を自分のドメインの DNS レコードに追加すればよい.

API Gateway で新規 API を作成したとき, default_cors_preflight_options= というパラメータで Cross Origin Resource Sharing (CORS) の設定を行っている. これは,ブラウザで走る Web アプリケーションと API を接続するときに必要な設定である.

アプリケーションのデプロイ

アプリケーションの中身が理解できたところで,早速デプロイを行ってみよう. デプロイの手順は,これまでのハンズオンとほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). シークレットキーの設定も忘れずに ( (#aws_cli_install)).

sh
# プロジェクトのディレクトリに移動
$ cd intro-aws/handson/bashoutter

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd intro-aws/handson/bashoutter

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイのコマンドが無事に実行されれば, figure_title のような出力が得られるはずである. ここで表示されている Bashoutter.BashoutterApiEndpoint = XXXX, Bashoutter.BucketUrl = YYYY の二つ文字列はあとで使うのでメモしておこう.

CDKデプロイ実行後の出力

AWS コンソールにログインして,デプロイされたスタックを確認してみよう. まずは,コンソールから API Gateway のページに行く. すると, figure_title のような画面が表示され,デプロイ済みの API エンドポイントの一覧が確認できる.

API Gateway コンソール画面 (1)

今回デプロイした "BashoutterApi" という名前の API をクリックすることで figure_title のような画面に遷移し,詳細情報を閲覧できる. GET /haiku, POST /haiku などが定義されていることが確認できる.

それぞれのメソッドをクリックすると,そのメソッドの詳細情報を確認できる. API Gateway は,前述したルーティングの機能だけでなく,認証機能などを追加することも可能である. このハンズオンではとくにこれらの機能は使用しないが, "Method Request" と書いてある項目などがそれに相当する. 次に, figure_title で画面右端の赤色で囲った部分に,この API で呼ばれる Lambda 関数が指定されていることに注目しよう. 関数名をクリックと,該当する Lambda のコンソールに遷移し,関数の中身を閲覧することが可能である.

API Gateway コンソール画面 (2)

次に, S3 のコンソール画面に移ってみよう. bashouter- で始まるランダムな名前のバケットが見つかるはずである (figure_title).

S3 コンソール画面

バケットの名前をクリックすることで,バケットの中身を確認してみよう. index.html のほか, css/, js/ などのディレクトリがあるのが確認できるだろう (figure_title). これらが,ウェブページの"枠"を定義している静的コンテンツである.

S3 バケットの中身

API リクエストを送信する

それでは,デプロイしたアプリケーションに対し,実際に API リクエストを送信してみよう. まずはコマンドラインから API を送信する演習を行おう. S3 に配置した GUI は一旦おいておく.

ここではコマンドラインから HTTP API リクエストを送信するためのシンプルな HTTP クライアントである HTTPie を使ってみよう. HTTPie は,スタックをデプロイするときに Python 仮想環境 (venv) を作成したとき,一緒にインストールされている. 念のためインストールがうまくいっているか確認するには,仮想環境を立ち上げたあとコマンドラインに http と打ってみる. ヘルプのメッセージが出力されたら準備 OK である.

まず,先ほどデプロイを実行したときに得られた API のエンドポイントの URL (Bashoutter.BashoutterApiEndpoint = XXXX で得られた XXXX の文字列) をコマンドラインの変数に設定しておく.

sh
$ export ENDPOINT_URL=XXXX
$ export ENDPOINT_URL=XXXX

次に,俳句の一覧を取得するため, GET /haiku の API を送信してみよう.

sh
$ http GET "${ENDPOINT_URL}/haiku"
$ http GET "${ENDPOINT_URL}/haiku"

現時点では,まだだれも俳句を投稿していないので,空の配列 ([]) が返ってくる.

それでは次に, POST /haiku を使って俳句を投稿してみよう.

sh
$ http POST "${ENDPOINT_URL}/haiku" \
username="松尾芭蕉" \
first="閑さや" \
second="岩にしみ入る" \
third="蝉の声"
$ http POST "${ENDPOINT_URL}/haiku" \
username="松尾芭蕉" \
first="閑さや" \
second="岩にしみ入る" \
third="蝉の声"

次のような出力が得られるだろう.

sh
HTTP/1.1 201 Created
Connection: keep-alive
Content-Length: 49
Content-Type: application/json
....
{
    "description": "Successfully added a new haiku"
}
HTTP/1.1 201 Created
Connection: keep-alive
Content-Length: 49
Content-Type: application/json
....
{
    "description": "Successfully added a new haiku"
}

新しい俳句を投稿することに成功したようである. 本当に俳句が追加されたか,再び GET リクエストを呼ぶことで確認してみよう.

sh
$ http GET "${ENDPOINT_URL}/haiku"

HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 258
Content-Type: application/json
...
[
    {
        "created_at": "2020-07-06T02:46:04+00:00",
        "first": "閑さや",
        "item_id": "7e91c5e4d7ad47909e0ac14c8bbab05b",
        "likes": 0.0,
        "second": "岩にしみ入る",
        "third": "蝉の声",
        "username": "松尾芭蕉"
    }
]
$ http GET "${ENDPOINT_URL}/haiku"

HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 258
Content-Type: application/json
...
[
    {
        "created_at": "2020-07-06T02:46:04+00:00",
        "first": "閑さや",
        "item_id": "7e91c5e4d7ad47909e0ac14c8bbab05b",
        "likes": 0.0,
        "second": "岩にしみ入る",
        "third": "蝉の声",
        "username": "松尾芭蕉"
    }
]

素晴らしい!

次に, PATCH /haiku/{item_id} を呼ぶことでこの俳句にいいねを追加してみよう. 一つ前のコマンドで取得した俳句の item_id を,次のコマンドの XXXX に代入した上で実行しよう.

sh
$ http PATCH "${ENDPOINT_URL}/haiku/XXXX"
$ http PATCH "${ENDPOINT_URL}/haiku/XXXX"

{"description": "OK"} という出力が得られるはずである. 再び GET リクエストを送ることで,いいね (likes) が 1 増えたことを確認しよう.

sh
$ http GET "${ENDPOINT_URL}/haiku"
...
[
    {
        ...
        "likes": 1.0,
        ...
    }
]
$ http GET "${ENDPOINT_URL}/haiku"
...
[
    {
        ...
        "likes": 1.0,
        ...
    }
]

最後に, DELETE リクエストを送ることで俳句をデータベースから削除しよう. XXXXitem_id の値で置き換えたうえで次のコマンドを実行する.

sh
$ http DELETE "${ENDPOINT_URL}/haiku/XXXX"
$ http DELETE "${ENDPOINT_URL}/haiku/XXXX"

再び GET リクエストを送ることで,返り値が空 ([]) になっていることを確認しよう.

これで,俳句の投稿・取得・削除そしていいねの追加,といった基本的な API がきちんと動作していることが確認できた.

大量の API リクエストをシミュレートする

さて,前節ではマニュアルで一つずつ俳句を投稿した. 多数のユーザーがいるような SNS では,1 秒間に数千件以上の投稿がされている. 今回はサーバーレスアーキテクチャを採用したことで,そのような瞬間的な大量アクセスにも容易に対応できるようなシステムが自動的に構築されている. このポイントを実証するため,ここでは大量の API が送信された状況をシミュレートしてみよう.

handson/bashoutter/client.py に,大量の API リクエストをシミュレートするためのプログラムが書かれている. このプログラムを使用すると, POST /haiku の API リクエストを指定された回数だけ実行することができる.

テストとして, API を 300 回実行してみよう. 次のコマンドを実行する.

sh
$ python client.py $ENDPOINT_URL post_many 300
$ python client.py $ENDPOINT_URL post_many 300

数秒のうちに実行が完了するだろう. これがもし,単一のサーバーからなる API だったとしたら,このような大量のリクエストの処理にはもっと時間がかかっただろう. 最悪の場合には,サーバーダウンにもつながっていたかもしれない. したがって,今回作成したサーバーレスアプリケーションは,とてもシンプルながらも 1 秒間に数百件の処理を行えるような,スケーラブルなクラウドシステムであることがわかる. サーバーレスでクラウドを設計することの利点を垣間見ることができただろうか?

先述のコマンドにより大量の俳句を投稿するとデータベースに無駄なデータがどんどん溜まってしまう. データベースを完全に空にするには,次のコマンドを使用する.

sh
$ python client.py $ENDPOINT_URL clear_database
$ python client.py $ENDPOINT_URL clear_database

Bashoutter GUI を動かしてみる

前節ではコマンドラインから API を送信する演習を行った. ウェブアプリケーションでは,これと同じことがウェブブラウザの背後で行われ,ページのコンテンツが表示されている ( (#fig:web_server) 参照). 最後に, API が GUI と統合されるとどうなるのか,見てみよう.

CDK のコードで, Public access mode の S3 バケットを作成したことを思い出してほしい. 最初のステップとして,ここにウェブサイトのコンテンツをアップロードしよう. ハンズオンのソースコードの中に gui/dist というフォルダが見つかるはずである. ここにはビルド済みのウェブサイトの静的コンテンツ (HTML/CSS/JavaScript) が入っている. AWS CLI のコマンドを使うことでこれらのファイルを S3 にアップロードしよう.

sh
$ aws s3 cp --recursive ./gui/dist s3://<BUCKET_NAME>
$ aws s3 cp --recursive ./gui/dist s3://<BUCKET_NAME>

コマンドを実行する際は, Bashoutter ハンズオンのディレクトリから行うこと (./gui/dist に注目),そして <BUCKET_NAME> にはデプロイした自身のバケットの名前が入る点に注意. 念のため,AWS コンソールにログインし,バケットにファイルがアップロードされている点を確認しておこう.

なお,今回は GUI の説明はとくに行わないが, Bashoutter のウェブサイトは Vue.jsVuetify という UI フレームワークを使って作成した. Vue を使うことで, Single page application (SPA) の技術でウェブサイトの画面がレンダリングされる. ソースコードは handson/bashoutter/gui のディレクトリの中にあるので,興味のある読者は確認してみるとよい.

アップトードが完了したところで,続いてデプロイを実行したときにコマンドラインの出力を見直してみよう. Bashoutter.BucketUrl= で与えられた URL が見つかるはずである (figure_title). これは,先述したとおり, Public access mode の S3 バケットの URL である.

ウェブブラウザを開き,アドレスバーに S3 の URL を入力しへアクセスしてみよう. すると, figure_title のようなページが表示されるはずである.

"Bashoutter" の GUI 画面

ページが表示されたら,一番上の "API Endpoint URL" と書いてあるテキストボックスに,今回デプロイした API Gateway の URL を入力する (今回のアプリケーションでは,API Gateway の URL はランダムに割り当てられるのでこのような GUI の仕様になっている). そうしたら,画面の "REFRESH" と書いてあるボタンを押してみよう. データベースに俳句が登録済みであれば,俳句の一覧が表示されるはずである. 各俳句の左下にあるハートのアイコンをクリックすることで, "like" の票を入れることができる.

新しい俳句を投稿するには,五七五と投稿者の名前を入力して, "POST" を押す. "POST" を押した後は,再び "REFRESH" ボタンを押すことで最新の俳句のリストをデータベースから取得する.

アプリケーションの削除

これで, Bashoutter プロジェクトが完成した! この SNS は,インターネットを通じて世界のどこからでもアクセスできる状態にある. また, 大量の API リクエストをシミュレートする で見たように,大量のユーザーの同時アクセスによる負荷がかかっても,柔軟にスケールが行われ遅延なく処理を行うことができる. 極めて簡素ながらも,立派なウェブサービスとしてのスペックは満たしているのである!

Bashoutter アプリを存分に楽しむことができたら,最後に忘れずにスタックを削除しよう.

コマンドラインからスタックの削除を実行するには,次のコマンドを使う.

sh
$ cdk destroy
$ cdk destroy

CDK のバージョンによっては S3 のバケットが空でないと, cdk destroy がエラーを出力する場合がある. この場合はスタックを削除する前に, S3 バケットの中身をすべて削除しなければならない.

コンソールから実行するには, S3 コンソールに行き,バケットの中身を開いたうえで,すべてのファイルを選択し, "Actions" → "Delete" を実行すればよいい.

コマンドラインから実行するには, 次のコマンドを使う. <BUCKET NAME> のところは,自分の バケットの名前 ("BashoutterBucketXXXX" というパターンの名前がついているはずである) に置き換えることを忘れずに.

sh
$ aws s3 rm <BUCKET NAME> --recursive
$ aws s3 rm <BUCKET NAME> --recursive

小括

ここまでが,本書第三部の内容であった.

第三部では,クラウドの応用として,一般の人に使ってもらうようなウェブアプリケーション・データベースをどのようにして作るのか,という点に焦点を当てて,説明を行った. その中で,従来的なクラウドシステムの設計と,ここ数年の最新の設計方法であるサーバーレスアーキテクチャについて解説した. (#sec_intro_serverless) では, AWS でのサーバーレスの実践として, Lambda, S3, DynamoDB のハンズオンを行った. 最後に, Hands-on #6: Bashoutter では,これらの技術を統合することで,完全サーバーレスなウェブアプリケーション "Bashoutter" を作成した.

これらの演習を通じて,世の中のウェブサービスがどのようにしてでき上がっているのか,少し理解が深まっただろうか? また,そのようなウェブアプリケーションを自分が作りたいと思ったとき,今回のハンズオンがその出発点となることができたならば幸いである.

]]>
Hands-on #6: Bashoutter

さて,最後のハンズオンとなる第六回では,これまで学んできたサーバーレスクラウドの技術を使って,簡単なウェブサービスを作ってみよう. 具体的には,人々が自分の作った俳句を投稿する SNS サービス (Bashoutter と名付ける) を作成してみよう. Lambda, DynamoDB, S3 などの技術をすべて盛り込み,シンプルながらもサーバーレスの利点を生かしたスケーラブルな SNS アプリが誕生する. 最終的には, figure_title のような,ミニマルではあるがとても現代風な SNS サイトが完成する!

ハンズオン#6で作製する SNS アプリケーション "Bashoutter"

準備

ハンズオンのソースコードは GitHub の handson/bashoutter に置いてある.

本ハンズオンの実行には,第一回ハンズオンで説明した準備 ( (#handson_01_prep)) が整っていることを前提とする. それ以外に必要な準備はない.

このハンズオンは,基本的に AWS の無料枠 の範囲内で実行できる.

アプリケーションの説明

API

今回のアプリケーションでは,人々からの俳句の投稿を受け付けたり,投稿された俳句の一覧を取得する,といった機能を実装したい. この機能を実現するための最小限の設計として, table_title に示すような四つの REST API を今回は実装する. 俳句を投稿する,閲覧する,削除するという基本的なデータ操作を行うための API が完備されている. また, PATCH /haiku/{item_id} は, {item_id} で指定された俳句に”いいね”をするために使用する.

Bashoutter API

GET /haiku

俳句の一覧を取得する

POST /haiku

新しい俳句を投稿する

PATCH /haiku/{item_id}

{item_id} で指定された俳句にお気に入り票を一つ入れる

DELETE /haiku/{item_id}

{item_id} で指定された俳句を削除する

それぞれの API のパラメータおよび返り値の詳細は,ハンズオンのソースコードの中の swagger.yml に定義してある.

Open API Specification (OAS; 少し前は Swagger Specification とよばれていた) は, REST API のための記述フォーマットである. OAS に従って API の仕様が記述されていると,簡単にドキュメンテーションを生成したり,クライアントアプリケーションを自動生成することができる. 今回用意した API 仕様 も, OAS に従って書いてある. 詳しくは Swagger の公式ドキュメンテーション などを参照.

アプリケーションアーキテクチャ

このハンズオンで作成するアプリケーションの概要を figure_title に示す.

ハンズオン#5で作製するアプリケーションのアーキテクチャ

簡単にまとめると,次のような設計である.

  • クライアントからの API リクエストは, API Gateway (後述)にまず送信され, API の URI で指定された Lambda 関数へ転送される.

  • それぞれの API のパス (リソース) ごとに独立した Lambda を用意する.

  • 俳句の情報 (作者,本文,投稿日時など) を記録するためのデータベース (DynamoDB) を用意する.

  • 各 Lambda 関数には, DynamoDB へのアクセス権を付与する.

  • 最後に,ウェブブラウザからコンテンツを表示できるよう, ウェブページの静的コンテンツを配信するための S3 バケットを用意する.クライアントはこの S3 バケットにアクセスすることで HTML/CSS/JS などのコンテンツを取得する.

それでは,プログラムのソースコードを見てみよう (handson/bashoutter/app.py).

python
class Bashoutter(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        # dynamoDB table to store haiku
        table = ddb.Table(
            self, "Bashoutter-Table",
            partition_key=ddb.Attribute(
                name="item_id",
                type=ddb.AttributeType.STRING
            ),
            billing_mode=ddb.BillingMode.PAY_PER_REQUEST,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        #
        bucket = s3.Bucket(
            self, "Bashoutter-Bucket",
            website_index_document="index.html",
            public_read_access=True,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        common_params = {
            "runtime": _lambda.Runtime.PYTHON_3_7,
            "environment": {
                "TABLE_NAME": table.table_name
            }
        }

        #
        # define Lambda functions
        get_haiku_lambda = _lambda.Function(
            self, "GetHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.get_haiku",
            memory_size=512,
            **common_params,
        )
        post_haiku_lambda = _lambda.Function(
            self, "PostHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.post_haiku",
            **common_params,
        )
        patch_haiku_lambda = _lambda.Function(
            self, "PatchHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.patch_haiku",
            **common_params,
        )
        delete_haiku_lambda = _lambda.Function(
            self, "DeleteHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.delete_haiku",
            **common_params,
        )

        #
        # grant permissions
        table.grant_read_data(get_haiku_lambda)
        table.grant_read_write_data(post_haiku_lambda)
        table.grant_read_write_data(patch_haiku_lambda)
        table.grant_read_write_data(delete_haiku_lambda)

        #
        # define API Gateway
        api = apigw.RestApi(
            self, "BashoutterApi",
            default_cors_preflight_options=apigw.CorsOptions(
                allow_origins=apigw.Cors.ALL_ORIGINS,
                allow_methods=apigw.Cors.ALL_METHODS,
            )
        )

        haiku = api.root.add_resource("haiku")
        haiku.add_method(
            "GET",
            apigw.LambdaIntegration(get_haiku_lambda)
        )
        haiku.add_method(
            "POST",
            apigw.LambdaIntegration(post_haiku_lambda)
        )

        haiku_item_id = haiku.add_resource("{item_id}")
        haiku_item_id.add_method(
            "PATCH",
            apigw.LambdaIntegration(patch_haiku_lambda)
        )
        haiku_item_id.add_method(
            "DELETE",
            apigw.LambdaIntegration(delete_haiku_lambda)
        )
class Bashoutter(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        # dynamoDB table to store haiku
        table = ddb.Table(
            self, "Bashoutter-Table",
            partition_key=ddb.Attribute(
                name="item_id",
                type=ddb.AttributeType.STRING
            ),
            billing_mode=ddb.BillingMode.PAY_PER_REQUEST,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        #
        bucket = s3.Bucket(
            self, "Bashoutter-Bucket",
            website_index_document="index.html",
            public_read_access=True,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        common_params = {
            "runtime": _lambda.Runtime.PYTHON_3_7,
            "environment": {
                "TABLE_NAME": table.table_name
            }
        }

        #
        # define Lambda functions
        get_haiku_lambda = _lambda.Function(
            self, "GetHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.get_haiku",
            memory_size=512,
            **common_params,
        )
        post_haiku_lambda = _lambda.Function(
            self, "PostHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.post_haiku",
            **common_params,
        )
        patch_haiku_lambda = _lambda.Function(
            self, "PatchHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.patch_haiku",
            **common_params,
        )
        delete_haiku_lambda = _lambda.Function(
            self, "DeleteHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.delete_haiku",
            **common_params,
        )

        #
        # grant permissions
        table.grant_read_data(get_haiku_lambda)
        table.grant_read_write_data(post_haiku_lambda)
        table.grant_read_write_data(patch_haiku_lambda)
        table.grant_read_write_data(delete_haiku_lambda)

        #
        # define API Gateway
        api = apigw.RestApi(
            self, "BashoutterApi",
            default_cors_preflight_options=apigw.CorsOptions(
                allow_origins=apigw.Cors.ALL_ORIGINS,
                allow_methods=apigw.Cors.ALL_METHODS,
            )
        )

        haiku = api.root.add_resource("haiku")
        haiku.add_method(
            "GET",
            apigw.LambdaIntegration(get_haiku_lambda)
        )
        haiku.add_method(
            "POST",
            apigw.LambdaIntegration(post_haiku_lambda)
        )

        haiku_item_id = haiku.add_resource("{item_id}")
        haiku_item_id.add_method(
            "PATCH",
            apigw.LambdaIntegration(patch_haiku_lambda)
        )
        haiku_item_id.add_method(
            "DELETE",
            apigw.LambdaIntegration(delete_haiku_lambda)
        )
  • ここで,俳句の情報を記録しておくための DynamoDB テーブルを定義している.

  • 静的コンテンツを配信するための S3 バケットを用意している.

  • それぞれの API で実行される Lambda 関数を定義している. 関数は Python3.7 で書かれており,コードは handson/bashoutter/api/api.py にある.

  • <3> で定義された Lambda 関数に対し,データベースへの読み書きのアクセス権限を付与している.

  • ここで,API Gateway により,各 API パスとそこで実行されるべき Lambda 関数を紐付けている.

それぞれの項目について,もう少し詳しく説明しよう.

Public access mode の S3 バケット

S3 のバケットを作成しているコードを見てみよう.

python
bucket = s3.Bucket(
    self, "Bashoutter-Bucket",
    website_index_document="index.html",
    public_read_access=True,
    removal_policy=core.RemovalPolicy.DESTROY
)
bucket = s3.Bucket(
    self, "Bashoutter-Bucket",
    website_index_document="index.html",
    public_read_access=True,
    removal_policy=core.RemovalPolicy.DESTROY
)

ここで注目してほしいのは public_read_access=True の部分だ. 前章で, S3 について説明を行ったときには触れなかったが, S3 には Public access mode という機能がある. Public access mode をオンにしておくと,バケットの中のファイルは認証なしで (i.e. インターネット上の誰でも) 閲覧できるようになる. この設定は,一般公開されているウェブサイトの静的なコンテンツを置いておくのに最適であり,多くのサーバーレスによるウェブサービスでこのような設計が行われる. public access mode を設定しておくと, http://XXXX.s3-website-ap-northeast-1.amazonaws.com/ のような固有の URL がバケットに対して付与される. そして,クライアントがこの URL にアクセスをすると,バケットの中にある index.html がクライアントに返され,ページがロードされる (どのファイルが返されるかは, website_index_document="index.html" の部分で設定している.)

なお,この時点ではバケットは空である. HTML/CSS/JS など静的コンテンツの配置は,デプロイを行った後ほどのステップで行う.

より本格的なウェブページを運用する際には, public access mode の S3 バケットに, CloudFront という機能を追加することが一般的である. CloudFront により, Content Delivery Nework (CDN) や暗号化された HTTPS 通信を設定することができる. CloudFront についての詳細は 公式ドキュメンテーション "What is Amazon CloudFront?" などを参照いただきたい.

今回のハンズオンでは説明の簡略化のため CloudFront の設定を行わなかったが,興味のある読者は次のリンクのプログラムが参考になるだろう.

今回の S3 バケットには, AWS によって付与されたランダムな URL がついている. これを. example.com のような自分のドメインでホストしたければ, AWS によって付与された URL を自分のドメインの DNS レコードに追加すればよい.

API のハンドラ関数

API リクエストが来たときに,リクエストされた処理を行う関数のことをハンドラ (handler) 関数とよぶ. GET /haiku の API に対してのハンドラ関数を Lambda で定義している部分を見てみよう.

python
get_haiku_lambda = _lambda.Function(
    self, "GetHaiku",
    code=_lambda.Code.from_asset("api"),
    handler="api.get_haiku",
    memory_size=512,
    **common_params
)
get_haiku_lambda = _lambda.Function(
    self, "GetHaiku",
    code=_lambda.Code.from_asset("api"),
    handler="api.get_haiku",
    memory_size=512,
    **common_params
)

簡単なところから見ていくと, memory_size=512 の箇所でメモリーの使用量を 512MB に指定している. また, code=_lambda.Code.from_asset("api") によって外部のディレクトリ (api/) を参照せよと指定しており, handler="api.get_haiku" のところで api.py というファイルの get_haiku() という関数をハンドラ関数として実行せよ,と定義している.

次に,ハンドラ関数として使用されている get_haiku() のコードを見てみよう (handson/bashoutter/api/api.py).

python
ddb = boto3.resource("dynamodb")
table = ddb.Table(os.environ["TABLE_NAME"])

def get_haiku(event, context):
    """
    handler for GET /haiku
    """
    try:
        response = table.scan()

        status_code = 200
        resp = response.get("Items")
    except Exception as e:
        status_code = 500
        resp = {"description": f"Internal server error. {str(e)}"}
    return {
        "statusCode": status_code,
        "headers": HEADERS,
        "body": json.dumps(resp, cls=DecimalEncoder)
    }
ddb = boto3.resource("dynamodb")
table = ddb.Table(os.environ["TABLE_NAME"])

def get_haiku(event, context):
    """
    handler for GET /haiku
    """
    try:
        response = table.scan()

        status_code = 200
        resp = response.get("Items")
    except Exception as e:
        status_code = 500
        resp = {"description": f"Internal server error. {str(e)}"}
    return {
        "statusCode": status_code,
        "headers": HEADERS,
        "body": json.dumps(resp, cls=DecimalEncoder)
    }

response = table.scan() で,俳句の格納された DynamoDB テーブルから,すべての要素を取り出している. もしなにもエラーが起きなければステータスコード 200 が返され,もしなにかエラーが起こればステータスコード 500 が返されるようになっている.

上記のような操作を,ほかの API についても繰り返すことで,すべての API のハンドラ関数が定義されている.

GET /haiku のハンドラ関数で, response = table.scan() という部分があるが,実はこれは最善の書き方ではない. DynamoDB の scan() メソッドは,最大で 1MB までのデータしか返さない. データベースのサイズが大きく, 1MB 以上のデータがある場合には,再帰的に scan() メソッドをよぶ必要がある. 詳しくは boto3 ドキュメンテーション を参照.

AWS における権限の管理 (IAM)

以下の部分のコードに注目してほしい.

python
table.grant_read_data(get_haiku_lambda)
table.grant_read_write_data(post_haiku_lambda)
table.grant_read_write_data(patch_haiku_lambda)
table.grant_read_write_data(delete_haiku_lambda)
table.grant_read_data(get_haiku_lambda)
table.grant_read_write_data(post_haiku_lambda)
table.grant_read_write_data(patch_haiku_lambda)
table.grant_read_write_data(delete_haiku_lambda)

これまでは説明の簡略化のためにあえて触れてこなかったが, AWS には IAM (Identity and Access Management) という重要な概念がある. IAM は基本的に,あるリソースがほかのリソースに対してどのような権限をもっているか,を規定するものである. Lambda は,デフォルトの状態ではほかのリソースにアクセスする権限をなにも有していない. したがって, Lambda 関数が DynamoDB のデータを読み書きするためには,それを許可するような IAM が Lambda 関数に付与されていなければならない.今回の S3 バケットには, AWS によって付与されたランダムな URL がついている. これを. example.com のような自分のドメインでホストしたければ, AWS によって付与された URL を自分のドメインの DNS レコードに追加すればよい.

CDK による dynamodb.Table オブジェクトには grant_read_write_data() という便利なメソッドが備わっており,アクセスを許可したい Lambda 関数を引数としてこのメソッドを呼ぶことで,データベースへの読み書きを許可する IAM を付与することができる. 同様に,CDK の s3.Bucket オブジェクトにも grant_read_write() というメソッドが備わっており,これによってバケットへの読み書きを許可することができる. このメソッドは,実は (#sec_aws_batch) で AWS Batch によるクラスターを構成した際に使用した. 興味のある読者は振り返ってコードを確認してみよう.

各リソースに付与する IAM は,必要最低限の権限を与えるにとどめるというのが基本方針である. これにより,セキュリティを向上させるだけでなく,意図していないプログラムからのデータベースへの読み書きを防止するという点で,バグを未然に防ぐことができる.

そのような理由により,このコードでは GET のハンドラー関数に対しては grant_read_data() によって, read 権限のみを付与している.

API Gateway

API Gateway とは, API の"入り口"として,API のリクエストパスに従って Lambda や EC2 などに接続を行うという機能を担う (figure_title). Lambda や EC2 によって行われた処理の結果は,再び API Gateway を経由してクライアントに返される. このように,クライアントとバックエンドサーバーの間に立ち, API のリソースパスに応じて接続先を振り分けるようなサーバーをルーター,あるいはリバースプロキシとよんだりする. 従来的には,ルーターにはそれ専用の仮想サーバーが置かれることが一般的であった. しかし, API Gateway はサーバーレスなルーターとして,固定されたサーバーを配置することなく, API のリクエストが来たときのみ起動し,API のルーティングを実行する. サーバーレスであることの当然の帰結として,アクセスの件数が増大したときにはそれにルーティングの処理能力を自動で増やす機能も備わっている.

API Gateway

API Gateway を配置することで,大量 (1 秒間に数千から数万件) の API リクエストに対応することのできるシステムを容易に構築することができる. API Gateway の料金は table_title のように設定されている. また,無料利用枠により,月ごとに 100 万件までのリクエストは 0 円で利用できる.

API Gateway の利用料金設定 (参照)
Number of Requests (per month)Price (per million)

First 333 million

$4.25

Next 667 million

$3.53

Next 19 billion

$3.00

Over 20 billion

$1.91

ソースコードの該当箇所を見てみよう.

python
#
api = apigw.RestApi(
    self, "BashoutterApi",
    default_cors_preflight_options=apigw.CorsOptions(
        allow_origins=apigw.Cors.ALL_ORIGINS,
        allow_methods=apigw.Cors.ALL_METHODS,
    )
)

#
haiku = api.root.add_resource("haiku")
#
haiku.add_method(
    "GET",
    apigw.LambdaIntegration(get_haiku_lambda)
)
haiku.add_method(
    "POST",
    apigw.LambdaIntegration(post_haiku_lambda)
)

#
haiku_item_id = haiku.add_resource("{item_id}")
#
haiku_item_id.add_method(
    "PATCH",
    apigw.LambdaIntegration(patch_haiku_lambda)
)
haiku_item_id.add_method(
    "DELETE",
    apigw.LambdaIntegration(delete_haiku_lambda)
)
#
api = apigw.RestApi(
    self, "BashoutterApi",
    default_cors_preflight_options=apigw.CorsOptions(
        allow_origins=apigw.Cors.ALL_ORIGINS,
        allow_methods=apigw.Cors.ALL_METHODS,
    )
)

#
haiku = api.root.add_resource("haiku")
#
haiku.add_method(
    "GET",
    apigw.LambdaIntegration(get_haiku_lambda)
)
haiku.add_method(
    "POST",
    apigw.LambdaIntegration(post_haiku_lambda)
)

#
haiku_item_id = haiku.add_resource("{item_id}")
#
haiku_item_id.add_method(
    "PATCH",
    apigw.LambdaIntegration(patch_haiku_lambda)
)
haiku_item_id.add_method(
    "DELETE",
    apigw.LambdaIntegration(delete_haiku_lambda)
)
  • 最初に, api = apigw.RestApi() により,空の API Gateway を作成している.

  • 次に, api.root.add_resource() のメソッドを呼ぶことで, /haiku という API パスを追加している.

  • 続いて, add_method() を呼ぶことで, GET, POST のメソッドを /haiku のパスに定義している.

  • さらに, haiku.add_resource("{item_id}") により, /haiku/{item_id} という API パスを追加している.

  • 最後に, add_method() を呼ぶことにより, PATCH, DELETE のメソッドを /haiku/{item_id} のパスに定義している.

このように, API Gateway の使い方は非常にシンプルで,逐次的に API パスとそこで実行されるメソッド・Lambda を記述していくだけでよい.

このプログラムで 新規 API を作成すると, ランダムな URL がその API のエンドポイントとして割り当てられる. これを. api.example.com のような自分のドメインでホストしたければ, AWS によって付与された URL を自分のドメインの DNS レコードに追加すればよい.

API Gateway で新規 API を作成したとき, default_cors_preflight_options= というパラメータで Cross Origin Resource Sharing (CORS) の設定を行っている. これは,ブラウザで走る Web アプリケーションと API を接続するときに必要な設定である.

アプリケーションのデプロイ

アプリケーションの中身が理解できたところで,早速デプロイを行ってみよう. デプロイの手順は,これまでのハンズオンとほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). シークレットキーの設定も忘れずに ( (#aws_cli_install)).

sh
# プロジェクトのディレクトリに移動
$ cd intro-aws/handson/bashoutter

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd intro-aws/handson/bashoutter

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイのコマンドが無事に実行されれば, figure_title のような出力が得られるはずである. ここで表示されている Bashoutter.BashoutterApiEndpoint = XXXX, Bashoutter.BucketUrl = YYYY の二つ文字列はあとで使うのでメモしておこう.

CDKデプロイ実行後の出力

AWS コンソールにログインして,デプロイされたスタックを確認してみよう. まずは,コンソールから API Gateway のページに行く. すると, figure_title のような画面が表示され,デプロイ済みの API エンドポイントの一覧が確認できる.

API Gateway コンソール画面 (1)

今回デプロイした "BashoutterApi" という名前の API をクリックすることで figure_title のような画面に遷移し,詳細情報を閲覧できる. GET /haiku, POST /haiku などが定義されていることが確認できる.

それぞれのメソッドをクリックすると,そのメソッドの詳細情報を確認できる. API Gateway は,前述したルーティングの機能だけでなく,認証機能などを追加することも可能である. このハンズオンではとくにこれらの機能は使用しないが, "Method Request" と書いてある項目などがそれに相当する. 次に, figure_title で画面右端の赤色で囲った部分に,この API で呼ばれる Lambda 関数が指定されていることに注目しよう. 関数名をクリックと,該当する Lambda のコンソールに遷移し,関数の中身を閲覧することが可能である.

API Gateway コンソール画面 (2)

次に, S3 のコンソール画面に移ってみよう. bashouter- で始まるランダムな名前のバケットが見つかるはずである (figure_title).

S3 コンソール画面

バケットの名前をクリックすることで,バケットの中身を確認してみよう. index.html のほか, css/, js/ などのディレクトリがあるのが確認できるだろう (figure_title). これらが,ウェブページの"枠"を定義している静的コンテンツである.

S3 バケットの中身

API リクエストを送信する

それでは,デプロイしたアプリケーションに対し,実際に API リクエストを送信してみよう. まずはコマンドラインから API を送信する演習を行おう. S3 に配置した GUI は一旦おいておく.

ここではコマンドラインから HTTP API リクエストを送信するためのシンプルな HTTP クライアントである HTTPie を使ってみよう. HTTPie は,スタックをデプロイするときに Python 仮想環境 (venv) を作成したとき,一緒にインストールされている. 念のためインストールがうまくいっているか確認するには,仮想環境を立ち上げたあとコマンドラインに http と打ってみる. ヘルプのメッセージが出力されたら準備 OK である.

まず,先ほどデプロイを実行したときに得られた API のエンドポイントの URL (Bashoutter.BashoutterApiEndpoint = XXXX で得られた XXXX の文字列) をコマンドラインの変数に設定しておく.

sh
$ export ENDPOINT_URL=XXXX
$ export ENDPOINT_URL=XXXX

次に,俳句の一覧を取得するため, GET /haiku の API を送信してみよう.

sh
$ http GET "${ENDPOINT_URL}/haiku"
$ http GET "${ENDPOINT_URL}/haiku"

現時点では,まだだれも俳句を投稿していないので,空の配列 ([]) が返ってくる.

それでは次に, POST /haiku を使って俳句を投稿してみよう.

sh
$ http POST "${ENDPOINT_URL}/haiku" \
username="松尾芭蕉" \
first="閑さや" \
second="岩にしみ入る" \
third="蝉の声"
$ http POST "${ENDPOINT_URL}/haiku" \
username="松尾芭蕉" \
first="閑さや" \
second="岩にしみ入る" \
third="蝉の声"

次のような出力が得られるだろう.

sh
HTTP/1.1 201 Created
Connection: keep-alive
Content-Length: 49
Content-Type: application/json
....
{
    "description": "Successfully added a new haiku"
}
HTTP/1.1 201 Created
Connection: keep-alive
Content-Length: 49
Content-Type: application/json
....
{
    "description": "Successfully added a new haiku"
}

新しい俳句を投稿することに成功したようである. 本当に俳句が追加されたか,再び GET リクエストを呼ぶことで確認してみよう.

sh
$ http GET "${ENDPOINT_URL}/haiku"

HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 258
Content-Type: application/json
...
[
    {
        "created_at": "2020-07-06T02:46:04+00:00",
        "first": "閑さや",
        "item_id": "7e91c5e4d7ad47909e0ac14c8bbab05b",
        "likes": 0.0,
        "second": "岩にしみ入る",
        "third": "蝉の声",
        "username": "松尾芭蕉"
    }
]
$ http GET "${ENDPOINT_URL}/haiku"

HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 258
Content-Type: application/json
...
[
    {
        "created_at": "2020-07-06T02:46:04+00:00",
        "first": "閑さや",
        "item_id": "7e91c5e4d7ad47909e0ac14c8bbab05b",
        "likes": 0.0,
        "second": "岩にしみ入る",
        "third": "蝉の声",
        "username": "松尾芭蕉"
    }
]

素晴らしい!

次に, PATCH /haiku/{item_id} を呼ぶことでこの俳句にいいねを追加してみよう. 一つ前のコマンドで取得した俳句の item_id を,次のコマンドの XXXX に代入した上で実行しよう.

sh
$ http PATCH "${ENDPOINT_URL}/haiku/XXXX"
$ http PATCH "${ENDPOINT_URL}/haiku/XXXX"

{"description": "OK"} という出力が得られるはずである. 再び GET リクエストを送ることで,いいね (likes) が 1 増えたことを確認しよう.

sh
$ http GET "${ENDPOINT_URL}/haiku"
...
[
    {
        ...
        "likes": 1.0,
        ...
    }
]
$ http GET "${ENDPOINT_URL}/haiku"
...
[
    {
        ...
        "likes": 1.0,
        ...
    }
]

最後に, DELETE リクエストを送ることで俳句をデータベースから削除しよう. XXXXitem_id の値で置き換えたうえで次のコマンドを実行する.

sh
$ http DELETE "${ENDPOINT_URL}/haiku/XXXX"
$ http DELETE "${ENDPOINT_URL}/haiku/XXXX"

再び GET リクエストを送ることで,返り値が空 ([]) になっていることを確認しよう.

これで,俳句の投稿・取得・削除そしていいねの追加,といった基本的な API がきちんと動作していることが確認できた.

大量の API リクエストをシミュレートする

さて,前節ではマニュアルで一つずつ俳句を投稿した. 多数のユーザーがいるような SNS では,1 秒間に数千件以上の投稿がされている. 今回はサーバーレスアーキテクチャを採用したことで,そのような瞬間的な大量アクセスにも容易に対応できるようなシステムが自動的に構築されている. このポイントを実証するため,ここでは大量の API が送信された状況をシミュレートしてみよう.

handson/bashoutter/client.py に,大量の API リクエストをシミュレートするためのプログラムが書かれている. このプログラムを使用すると, POST /haiku の API リクエストを指定された回数だけ実行することができる.

テストとして, API を 300 回実行してみよう. 次のコマンドを実行する.

sh
$ python client.py $ENDPOINT_URL post_many 300
$ python client.py $ENDPOINT_URL post_many 300

数秒のうちに実行が完了するだろう. これがもし,単一のサーバーからなる API だったとしたら,このような大量のリクエストの処理にはもっと時間がかかっただろう. 最悪の場合には,サーバーダウンにもつながっていたかもしれない. したがって,今回作成したサーバーレスアプリケーションは,とてもシンプルながらも 1 秒間に数百件の処理を行えるような,スケーラブルなクラウドシステムであることがわかる. サーバーレスでクラウドを設計することの利点を垣間見ることができただろうか?

先述のコマンドにより大量の俳句を投稿するとデータベースに無駄なデータがどんどん溜まってしまう. データベースを完全に空にするには,次のコマンドを使用する.

sh
$ python client.py $ENDPOINT_URL clear_database
$ python client.py $ENDPOINT_URL clear_database

Bashoutter GUI を動かしてみる

前節ではコマンドラインから API を送信する演習を行った. ウェブアプリケーションでは,これと同じことがウェブブラウザの背後で行われ,ページのコンテンツが表示されている ( (#fig:web_server) 参照). 最後に, API が GUI と統合されるとどうなるのか,見てみよう.

CDK のコードで, Public access mode の S3 バケットを作成したことを思い出してほしい. 最初のステップとして,ここにウェブサイトのコンテンツをアップロードしよう. ハンズオンのソースコードの中に gui/dist というフォルダが見つかるはずである. ここにはビルド済みのウェブサイトの静的コンテンツ (HTML/CSS/JavaScript) が入っている. AWS CLI のコマンドを使うことでこれらのファイルを S3 にアップロードしよう.

sh
$ aws s3 cp --recursive ./gui/dist s3://<BUCKET_NAME>
$ aws s3 cp --recursive ./gui/dist s3://<BUCKET_NAME>

コマンドを実行する際は, Bashoutter ハンズオンのディレクトリから行うこと (./gui/dist に注目),そして <BUCKET_NAME> にはデプロイした自身のバケットの名前が入る点に注意. 念のため,AWS コンソールにログインし,バケットにファイルがアップロードされている点を確認しておこう.

なお,今回は GUI の説明はとくに行わないが, Bashoutter のウェブサイトは Vue.jsVuetify という UI フレームワークを使って作成した. Vue を使うことで, Single page application (SPA) の技術でウェブサイトの画面がレンダリングされる. ソースコードは handson/bashoutter/gui のディレクトリの中にあるので,興味のある読者は確認してみるとよい.

アップトードが完了したところで,続いてデプロイを実行したときにコマンドラインの出力を見直してみよう. Bashoutter.BucketUrl= で与えられた URL が見つかるはずである (figure_title). これは,先述したとおり, Public access mode の S3 バケットの URL である.

ウェブブラウザを開き,アドレスバーに S3 の URL を入力しへアクセスしてみよう. すると, figure_title のようなページが表示されるはずである.

"Bashoutter" の GUI 画面

ページが表示されたら,一番上の "API Endpoint URL" と書いてあるテキストボックスに,今回デプロイした API Gateway の URL を入力する (今回のアプリケーションでは,API Gateway の URL はランダムに割り当てられるのでこのような GUI の仕様になっている). そうしたら,画面の "REFRESH" と書いてあるボタンを押してみよう. データベースに俳句が登録済みであれば,俳句の一覧が表示されるはずである. 各俳句の左下にあるハートのアイコンをクリックすることで, "like" の票を入れることができる.

新しい俳句を投稿するには,五七五と投稿者の名前を入力して, "POST" を押す. "POST" を押した後は,再び "REFRESH" ボタンを押すことで最新の俳句のリストをデータベースから取得する.

アプリケーションの削除

これで, Bashoutter プロジェクトが完成した! この SNS は,インターネットを通じて世界のどこからでもアクセスできる状態にある. また, 大量の API リクエストをシミュレートする で見たように,大量のユーザーの同時アクセスによる負荷がかかっても,柔軟にスケールが行われ遅延なく処理を行うことができる. 極めて簡素ながらも,立派なウェブサービスとしてのスペックは満たしているのである!

Bashoutter アプリを存分に楽しむことができたら,最後に忘れずにスタックを削除しよう.

コマンドラインからスタックの削除を実行するには,次のコマンドを使う.

sh
$ cdk destroy
$ cdk destroy

CDK のバージョンによっては S3 のバケットが空でないと, cdk destroy がエラーを出力する場合がある. この場合はスタックを削除する前に, S3 バケットの中身をすべて削除しなければならない.

コンソールから実行するには, S3 コンソールに行き,バケットの中身を開いたうえで,すべてのファイルを選択し, "Actions" → "Delete" を実行すればよいい.

コマンドラインから実行するには, 次のコマンドを使う. <BUCKET NAME> のところは,自分の バケットの名前 ("BashoutterBucketXXXX" というパターンの名前がついているはずである) に置き換えることを忘れずに.

sh
$ aws s3 rm <BUCKET NAME> --recursive
$ aws s3 rm <BUCKET NAME> --recursive

小括

ここまでが,本書第三部の内容であった.

第三部では,クラウドの応用として,一般の人に使ってもらうようなウェブアプリケーション・データベースをどのようにして作るのか,という点に焦点を当てて,説明を行った. その中で,従来的なクラウドシステムの設計と,ここ数年の最新の設計方法であるサーバーレスアーキテクチャについて解説した. (#sec_intro_serverless) では, AWS でのサーバーレスの実践として, Lambda, S3, DynamoDB のハンズオンを行った. 最後に, Hands-on #6: Bashoutter では,これらの技術を統合することで,完全サーバーレスなウェブアプリケーション "Bashoutter" を作成した.

これらの演習を通じて,世の中のウェブサービスがどのようにしてでき上がっているのか,少し理解が深まっただろうか? また,そのようなウェブアプリケーションを自分が作りたいと思ったとき,今回のハンズオンがその出発点となることができたならば幸いである.

]]>
<![CDATA[Hands-on #1: 初めての EC2 インスタンスを起動する ]]> https://note.toshiki.dev/development/aws/handson-ec2 https://note.toshiki.dev/development/aws/handson-ec2 Thu, 01 Jul 2021 00:00:00 GMT Hands-on #1: 初めての EC2 インスタンスを起動する

ハンズオンの第一回では, CDK を使って EC2 のインスタンス(仮想サーバー)を作成し,SSH でサーバーにログインする,という演習を行う. このハンズオンを終えれば,あなたは自分だけのサーバーを AWS 上に立ち上げ,自由に計算を走らせることができるようになるのである!

準備

ハンズオンのソースコードは GitHub の handson/ec2-get-started に置いてある.

このハンズオンは,基本的に AWS の無料枠 の範囲内で実行することができる.

まずは,ハンズオンを実行するための環境を整える. これらの環境整備は,後のハンズオンでも前提となるものなので確実にミスなく行っていただきたい.

  • AWS Account: ハンズオンを実行するには個人の AWS アカウントが必要である. AWS アカウントの取得については (#sec:create_aws_account) を参照のこと.

  • Python と Node.js: 本ハンズオンを実行するには,Python (3.6 以上),Node.js (12.0 以上) がインストールされていなければならない.

  • AWS CLI: AWS CLI のインストールについては, (#aws_cli_install) を参照. ここに記載されている認証鍵の設定も済ませておくこと.

  • AWS CDK: AWS CDK のインストールについては, (#aws_cdk_install) を参照.

  • ソースコードのダウンロード: 本ハンズオンで使用するプログラムのソースコードを,以下のコマンドを使って GitHub からダウンロードする.

sh
$ git clone https://github.com/tomomano/learn-aws-by-coding.git
$ git clone https://github.com/tomomano/learn-aws-by-coding.git

あるいは, https://github.com/tomomano/learn-aws-by-coding のページに行って,右上のダウンロードボタンからダウンロードすることもできる.

Docker を使用する場合

Python, Node.js, AWS CDK など,ハンズオンのプログラムを実行するために必要なプログラム/ライブラリがインストール済みの Docker image を用意した. また,ハンズオンのソースコードもパッケージ済みである. Docker の使い方を知っている読者は,これを使えば,諸々のインストールをする必要なく,すぐにハンズオンのプログラムを実行できる.

使用方法については (#sec_handson_docker) を参照のこと.

SSH

SSH (secure shell) は Unix 系のリモートサーバーに安全にアクセスするためのツールである. 本ハンズオンでは, SSH を使って仮想サーバーにアクセスする. SSH に慣れていない読者のため,簡単な説明をここで行おう.

SSH による通信はすべて暗号化されているので,機密情報をインターネットを介して安全に送受信することができる. 本ハンズオンで,リモートのサーバーにアクセスするための SSH クライアントがローカルマシンにインストールされている必要がある. SSH クライアントは Linux/Mac には標準搭載されている. Windows の場合は WSL をインストールすることで SSH クライアントを利用することを推奨する ( (#environments) を参照).

SSH コマンドの基本的な使い方を次に示す. <host name> はアクセスする先のサーバーの IP アドレスや DNS によるホストネームが入る. <user name> は接続する先のユーザー名である.

sh
$ ssh <user name>@<host name>
$ ssh <user name>@<host name>

SSH は平文のパスワードによる認証を行うこともできるが,より強固なセキュリティを施すため,公開鍵暗号方式(Public Key Cryptography)による認証を行うことが強く推奨されており, EC2 はこの方法でしかアクセスを許していない. 公開鍵暗号方式の仕組みについては各自勉強してほしい. 本ハンズオンにおいて大事なことは,EC2 インスタンスが公開鍵(Public key)を保持し,クライアントとなるコンピュータ(読者自身のコンピュータ)が秘密鍵(Private key)を保持する,という点である. EC2 のインスタンスには秘密鍵を持ったコンピュータのみがアクセスすることができる.逆に言うと,秘密鍵が漏洩すると第三者もサーバーにアクセスできることになるので,秘密鍵は絶対に漏洩することのないよう注意して管理する

SSH コマンドでは,ログインのために使用する秘密鍵ファイルを -i もしくは --identity_file のオプションで指定することができる. たとえば,次のように使う.

sh
$ ssh -i Ec2SecretKey.pem <user name>@<host name>
$ ssh -i Ec2SecretKey.pem <user name>@<host name>

アプリケーションの説明

このハンズオンで作成するアプリケーションの概要を figure_title に示す.

ハンズオン#1で作製するアプリケーションのアーキテクチャ

このアプリケーションではまず,VPC (Virtual Private Cloud) を使ってプライベートな仮想ネットワーク環境を立ち上げている. その VPC の public subnet の内側に,EC2 (Elatic Compute Cloud) の仮想サーバーを配置する. さらに,セキュリティのため, Security Group による EC2 インスタンスへのアクセス制限を設定している. このようにして作成された仮想サーバーに,SSH を使ってアクセスし,簡単な計算を行う.

figure_title のようなアプリケーションを,CDK を使って構築する.

早速ではあるが,今回のハンズオンで使用するプログラムを見てみよう (handson/ec2-get-started/app.py).

python
class MyFirstEc2(core.Stack):

    def __init__(self, scope: core.App, name: str, key_name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        vpc = ec2.Vpc(
            self, "MyFirstEc2-Vpc",
            max_azs=1,
            cidr="10.10.0.0/23",
            subnet_configuration=[
                ec2.SubnetConfiguration(
                    name="public",
                    subnet_type=ec2.SubnetType.PUBLIC,
                )
            ],
            nat_gateways=0,
        )

        #
        sg = ec2.SecurityGroup(
            self, "MyFirstEc2Vpc-Sg",
            vpc=vpc,
            allow_all_outbound=True,
        )
        sg.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(22),
        )

        #
        host = ec2.Instance(
            self, "MyFirstEc2Instance",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ec2.MachineImage.latest_amazon_linux(),
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            security_group=sg,
            key_name=key_name
        )
class MyFirstEc2(core.Stack):

    def __init__(self, scope: core.App, name: str, key_name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        vpc = ec2.Vpc(
            self, "MyFirstEc2-Vpc",
            max_azs=1,
            cidr="10.10.0.0/23",
            subnet_configuration=[
                ec2.SubnetConfiguration(
                    name="public",
                    subnet_type=ec2.SubnetType.PUBLIC,
                )
            ],
            nat_gateways=0,
        )

        #
        sg = ec2.SecurityGroup(
            self, "MyFirstEc2Vpc-Sg",
            vpc=vpc,
            allow_all_outbound=True,
        )
        sg.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(22),
        )

        #
        host = ec2.Instance(
            self, "MyFirstEc2Instance",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ec2.MachineImage.latest_amazon_linux(),
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            security_group=sg,
            key_name=key_name
        )
  • まず最初に,VPC を定義する.

  • 次に, security group (SG) を定義している. ここでは,任意の IPv4 のアドレスからの,ポート 22 (SSH の接続に使用される)への接続を許可している. それ以外の接続は拒絶される.

  • 最後に,上記で作った VPC と SG が付与された EC2 インスタンスを作成している. インスタンスタイプは t2.micro を選択し, Amazon Linux を OS として設定している.

それぞれについて,もう少し詳しく説明しよう.

VPC (Virtual Private Cloud)

VPC のアイコン.

VPC

VPC は AWS 上にプライベートな仮想ネットワーク環境を構築するツールである.高度な計算システムを構築するには,複数のサーバーを連動させて計算を行う必要があるが,そのような場合に互いのアドレスなどを管理する必要があり,そういった目的で VPC は有用である.

本ハンズオンでは,サーバーは一つしか起動しないので,VPC の恩恵はよく分からないかもしれない.しかし,EC2 インスタンスは必ず VPC の中に配置されなければならない,という制約があるので,このハンズオンでもミニマルな VPC を構成している.

興味のある読者のために,VPC のコードについてもう少し詳しく説明しよう.

python
vpc = ec2.Vpc(
    self, "MyFirstEc2-Vpc",
    max_azs=1,
    cidr="10.10.0.0/23",
    subnet_configuration=[
        ec2.SubnetConfiguration(
            name="public",
            subnet_type=ec2.SubnetType.PUBLIC,
        )
    ],
    nat_gateways=0,
)
vpc = ec2.Vpc(
    self, "MyFirstEc2-Vpc",
    max_azs=1,
    cidr="10.10.0.0/23",
    subnet_configuration=[
        ec2.SubnetConfiguration(
            name="public",
            subnet_type=ec2.SubnetType.PUBLIC,
        )
    ],
    nat_gateways=0,
)
  • max_azs=1 : このパラメータは,前章で説明した avaialibility zone (AZ) を設定している. このハンズオンでは,特にデータセンターの障害などを気にする必要はないので 1 にしている.

  • cidr="10.10.0.0/23" : このパラメータは,VPC 内の IPv4 のレンジを指定している. CIDR 記法については, Wikipediaなどを参照. 10.10.0.0/2310.10.0.0 から 10.10.1.255 までの 512 個の連続したアドレス範囲を指している. つまり,この VPC では最大で 512 個のユニークな IPv4 アドレスが使えることになる. 今回はサーバーは一つなので 512 個は明らかに多すぎるが,VPC はアドレスの数はどれだけ作成しても無料なので,多めに作成した.

  • subnet_configuration=... : このパラメータは,VPC にどのようなサブネットを作るか,を決めている. サブネットの種類には private subnetpublic subnet の二種類がある. private subnet は基本的にインターネットとは遮断されたサブネット環境である. インターネットと繋がっていないので,セキュリティは極めて高く, VPC 内のサーバーとのみ通信を行えばよい EC2 インスタンスはここに配置する. Public subnet とはインターネットに繋がったサブネットである. 本ハンズオンで作成するサーバーは,外から SSH でログインを行いたいので, Public subnet 内に配置する. より詳細な記述は 公式ドキュメンテーション を参照.

  • natgateways=0 : これは少し高度な内容なので省略する (興味のある読者は 公式ドキュメンテーションを参照). が,これを 0 にしておかないと,NAT Gateway の利用料金が発生してしまうので,注意!

Security Group

Security group (SG) は, EC2 インスタンスに付与することのできる仮想ファイアーウォールである. たとえば,特定の IP アドレスから来た接続を許可・拒絶したり (インバウンド・トラフィックの制限) ,逆に特定の IP アドレスへのアクセスを禁止したり (アウトバウンド・トラフィックの制限) することができる.

コードの該当部分を見てみよう.

python
sg = ec2.SecurityGroup(
    self, "MyFirstEc2Vpc-Sg",
    vpc=vpc,
    allow_all_outbound=True,
)
sg.add_ingress_rule(
    peer=ec2.Peer.any_ipv4(),
    connection=ec2.Port.tcp(22),
)
sg = ec2.SecurityGroup(
    self, "MyFirstEc2Vpc-Sg",
    vpc=vpc,
    allow_all_outbound=True,
)
sg.add_ingress_rule(
    peer=ec2.Peer.any_ipv4(),
    connection=ec2.Port.tcp(22),
)

本ハンズオンでは, SSH による外部からの接続を許容するため, sg.add_ingress_rule(peer=ec2.Peer.any_ipv4(), connection=ec2.Port.tcp(22)) により,すべての IPv4 アドレスからのポート 22 番へのアクセスを許容している. また, SSH で EC2 インスタンスにログインしたのち,インターネットからプログラムなどをダウンロードできるよう, allow_all_outbound=True のパラメータを設定している.

SSH はデフォルトでは 22 番ポートを使用するのが慣例である.

セキュリティ上の観点からは,SSH の接続は自宅や大学・職場など特定の地点からの接続のみを許す方が望ましい.

EC2 (Elastic Compute Cloud)

EC2 のアイコン.

EC2

EC2 は AWS 上に仮想サーバーを立ち上げるサービスである. 個々の起動状態にある仮想サーバーのことをインスタンス (instance) とよぶ (しかし,口語的なコミュニケーションにおいては,サーバーとインスタンスという言葉は相互互換的に用いられることが多い).

EC2 では用途に応じて様々なインスタンスタイプが提供されている. table_title に,代表的なインスタンスタイプの例を挙げる (執筆時点での情報). EC2 のインスタンスタイプのすべてのリストは 公式ドキュメンテーション "Amazon EC2 Instance Types" で見ることができる.

EC2 instance types

Instance vCPU Memory (GiB) Network bandwidth (Gbps) Price per hour ($)
t2.micro 1 1 - 0.0116
t2.small 1 2 - 0.023
t2.medium 2 4 - 0.0464
c5.24xlarge 96 192 25 4.08
c5n.18xlarge 72 192 100 3.888
x1e.16xlarge 64 1952 10 13.344

table_title からわかるように, CPU は 1 コアから 96 コアまで,メモリーは 1GB から 2TB 以上まで,ネットワーク帯域は最大で 100Gbps まで,幅広く選択することができる. また,時間あたりの料金は,CPU・メモリーの占有数にほぼ比例する形で増加する. EC2 はサーバーの起動時間を秒単位で記録しており,利用料金は使用時間に比例する形で決定される. 例えば, t2.medium のインスタンスを 10 時間起動した場合,0.0464 * 10 = 0.464 ドルの料金が発生する.

AWS には 無料利用枠 というものがあり, t2.micro であれば月に 750 時間までは無料で利用することができる.

table_title の価格は us-east-1 のものである. リージョンによって多少価格設定が異なる.

上記で t2.micro の $0.0116 / hour という金額は, On-demand インスタンスというタイプを選択した場合の価格である. EC2 ではほかに, Spot instance とよばれるインスタンスも存在しする. Spot instance は,AWS のデータセンターの負荷が増えた場合,ユーザーのプログラムが実行中であっても AWS の判断により強制シャットダウンされる,という不便さを抱えているのだが,その分大幅に安い料金設定になっている. AWS で一時的に生じた余剰な空き CPU をユーザーに割安で貸し出す,という発想である. 科学計算やウェブサーバーなどの用途でコストを削減する目的で, Spot Instance を活用する事例も多数報告されている.

EC2 インスタンスを定義しているコードの該当部分を見てみよう.

python
host = ec2.Instance(
    self, "MyFirstEc2Instance",
    instance_type=ec2.InstanceType("t2.micro"),
    machine_image=ec2.MachineImage.latest_amazon_linux(),
    vpc=vpc,
    vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
    security_group=sg,
    key_name=key_name
)
host = ec2.Instance(
    self, "MyFirstEc2Instance",
    instance_type=ec2.InstanceType("t2.micro"),
    machine_image=ec2.MachineImage.latest_amazon_linux(),
    vpc=vpc,
    vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
    security_group=sg,
    key_name=key_name
)

ここでは, t2.micro というインスタンスタイプを選択している. さらに, machine_image として, Amazon Linux を選択している (Machine image は OS と似た概念である. Machine image については, (#sec_jupyter_and_deep_learning) でより詳しく触れる). さらに,上で定義した VPC, SG をこのインスタンスに付与している.

以上が,今回使用するプログラムの簡単な解説であった. ミニマルな形のプログラムではあるが,仮想サーバーを作成するのに必要なステップがおわかりいただけただろうか?

プログラムを実行する

さて,ハンズオンのコードの理解ができたところで,プログラムを実際に実行してみよう.繰り返しになるが, 準備 での準備ができていることが前提である.

Python の依存ライブラリのインストール

まずは,Python の依存ライブラリをインストールする.以下では,Python のライブラリを管理するツールとして, venv を使用する.

まずは, handson/ec2-get-started のディレクトリに移動しよう.

sh
$ cd handson/ec2-get-started
$ cd handson/ec2-get-started

ディレクトリを移動したら, venv で新しい仮想環境を作成し,インストールを実行する.

sh
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

これで Python の環境構築は完了だ.

venv の簡単な説明は (#venv_quick_guide) に記述してある.

環境によっては pip ではなく pip3 あるいは python3 -m pip に置き換える必要がある.

AWS のシークレットキーをセットする

AWS CLI および AWS CDK を使うには, AWS のシークレットキーが設定されている必要がある. シークレットキーの発行については (#aws_secrets) を参照のこと. シークレットキーを発行したら, (#aws_cli_install) を参照し,コマンドラインの設定を行う.

手順をここに短く要約すると,一つ目の方法は AWS_ACCESS_KEY_ID などの環境変数を設定するやり方である. もう一つの方法は, ~/.aws/credentials に認証情報を保存しておく方式である. シークレットキーの設定は AWS CLI/CDK を使用するうえで共通のステップになるので,しっかりと理解しておくように.

SSH 鍵を生成

EC2 インスタンスには SSH を使ってログインする. EC2 インスタンスを作成するのに先行して,今回のハンズオンで専用に使う SSH の公開鍵・秘密鍵のペアを準備する必要がある.

次の AWS CLI コマンドにより, HirakeGoma という名前のついた鍵を生成する.

sh
$ export KEY_NAME="HirakeGoma"
$ aws ec2 create-key-pair --key-name ${KEY_NAME} --query 'KeyMaterial' --output text > ${KEY_NAME}.pem
$ export KEY_NAME="HirakeGoma"
$ aws ec2 create-key-pair --key-name ${KEY_NAME} --query 'KeyMaterial' --output text > ${KEY_NAME}.pem

このコマンドを実行すると,現在のディレクトリに HirakeGoma.pem というファイルが作成される.これが,サーバーにアクセスするための秘密鍵である. SSH でこの鍵を使うため, ~/.ssh/ のディレクトリに鍵を移動する. さらに,秘密鍵が書き換えられたり第三者に閲覧されないよう,ファイルのアクセス権限を 400 に設定する.

sh
$ mv HirakeGoma.pem ~/.ssh/
$ chmod 400 ~/.ssh/HirakeGoma.pem
$ mv HirakeGoma.pem ~/.ssh/
$ chmod 400 ~/.ssh/HirakeGoma.pem

デプロイを実行

これまでのステップで, EC2 インスタンスをデプロイするための準備が整った! 早速,次のコマンドによりアプリケーションを AWS にデプロイしよう. -c key_name="HirakeGoma" というオプションで,先ほど生成した HirakeGoma という名前の鍵を使うよう指定している.

sh
$ cdk deploy -c key_name="HirakeGoma"
$ cdk deploy -c key_name="HirakeGoma"

このコマンドを実行すると, VPC, EC2 などが AWS 上に展開される. そして,コマンドの出力の最後に figure_title のような出力が得られるはずである. 出力の中で InstancePublicIp に続く数字が,起動したインスタンスのパブリック IP アドレスである. IP アドレスはデプロイごとにランダムなアドレスが割り当てられる.

CDKデプロイ実行後の出力

SSH でログイン

早速,SSH  で接続してみよう.

sh
$ ssh -i ~/.ssh/HirakeGoma.pem ec2-user@<IP address>
$ ssh -i ~/.ssh/HirakeGoma.pem ec2-user@<IP address>

-i オプションで,先ほど生成した秘密鍵を指定している. EC2 インスタンスにはデフォルトで ec2-user という名前のユーザーが作られているので,それを使用する. 最後に, <IP address> の部分は自身が作成した EC2 インスタンスの IP アドレスで置き換える (12.345.678.9 など).

ログインに成功すると, figure_title のような画面が表示される. リモートのサーバーにログインしているので,プロンプトが [ec2-user@ip-10-10-1-217 ~]$ のようになっていることを確認しよう.

SSH で EC2 インスタンスにログイン

おめでとう!これで,めでたく AWS 上に EC2 仮想サーバーを起動し,リモートからアクセスできるようになった!

起動した EC2 インスタンスで遊んでみる

せっかく新しいインスタンスを起動したので,少し遊んでみよう.

ログインした EC2 インスタンスで,次のコマンドを実行してみよう. CPU の情報を取得することができる.

sh
$ cat /proc/cpuinfo

processor       : 0
vendor_id       : GenuineIntel
cpu family      : 6
model           : 63
model name      : Intel(R) Xeon(R) CPU E5-2676 v3 @ 2.40GHz
stepping        : 2
microcode       : 0x43
cpu MHz         : 2400.096
cache size      : 30720 KB
$ cat /proc/cpuinfo

processor       : 0
vendor_id       : GenuineIntel
cpu family      : 6
model           : 63
model name      : Intel(R) Xeon(R) CPU E5-2676 v3 @ 2.40GHz
stepping        : 2
microcode       : 0x43
cpu MHz         : 2400.096
cache size      : 30720 KB

次に,実行中のプロセスやメモリの消費を見てみよう.

bash
$  top -n 1

top - 09:29:19 up 43 min,  1 user,  load average: 0.00, 0.00, 0.00
Tasks:  76 total,   1 running,  51 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.3%us,  0.3%sy,  0.1%ni, 98.9%id,  0.2%wa,  0.0%hi,  0.0%si,  0.2%st
Mem:   1009140k total,   270760k used,   738380k free,    14340k buffers
Swap:        0k total,        0k used,        0k free,   185856k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
    1 root      20   0 19696 2596 2268 S  0.0  0.3   0:01.21 init
    2 root      20   0     0    0    0 S  0.0  0.0   0:00.00 kthreadd
    3 root      20   0     0    0    0 I  0.0  0.0   0:00.00 kworker/0:0
$  top -n 1

top - 09:29:19 up 43 min,  1 user,  load average: 0.00, 0.00, 0.00
Tasks:  76 total,   1 running,  51 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.3%us,  0.3%sy,  0.1%ni, 98.9%id,  0.2%wa,  0.0%hi,  0.0%si,  0.2%st
Mem:   1009140k total,   270760k used,   738380k free,    14340k buffers
Swap:        0k total,        0k used,        0k free,   185856k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
    1 root      20   0 19696 2596 2268 S  0.0  0.3   0:01.21 init
    2 root      20   0     0    0    0 S  0.0  0.0   0:00.00 kthreadd
    3 root      20   0     0    0    0 I  0.0  0.0   0:00.00 kworker/0:0

t2.micro インスタンスなので, 1009140k = 1GB のメモリーがあることがわかる.

今回起動したインスタンスには Python 2 はインストール済みだが, Python 3 は入っていない. Python 3.6 のインストールを行ってみよう. インストールは簡単である.

sh
$ sudo yum update -y
$ sudo yum install -y python36
$ sudo yum update -y
$ sudo yum install -y python36

インストールした Python を起動してみよう.

sh
$ python3
Python 3.6.10 (default, Feb 10 2020, 19:55:14)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
$ python3
Python 3.6.10 (default, Feb 10 2020, 19:55:14)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Python のインタープリタが起動した! Ctrl + D あるいは exit() と入力することで,インタープリタを閉じることができる.

さて,サーバーでのお遊びはこんなところにしておこう (興味があれば各自いろいろと試してみると良い) . 次のコマンドでログアウトする.

sh
$ exit
$ exit

AWS コンソールから確認

これまでは,すべてコマンドラインから EC2 に関連する操作を行ってきた. EC2 インスタンスの状態を確認したり,サーバーをシャットダウンするなどの操作は,AWS コンソールから実行することもできる. 軽くこれを紹介しよう.

まず,ウェブブラウザを開いて AWS コンソールにログインする. ログインしたら, Services から EC2 を検索(選択)する. 次に,左のサイドバーの Instances とページをたどる. すると, figure_title のような画面が得られるはずである. この画面で,自分のアカウントの管理下にあるインスタンスを確認できる. 同様に,VPC・SG についてもコンソールから確認できる.

EC2 コンソール画面

コンソール右上で,正しいリージョン (今回の場合は ap-northeast-1, Tokyo) が選択されているか,注意する!

前章で CloudFormation について触れたが,今回デプロイしたアプリケーションも,CloudFormation のスタックとして管理されている. スタック (stack) とは, AWS リソースの集合のことを指す. 今回の場合は, VPC/EC2/SG などがスタックの中に含まれている. コンソールで CloudFormation のページに行ってみよう (figure_title).

CloudFormation コンソール画面

"MyFirstEc2" という名前のスタックがあることが確認できる. クリックをして中身を見てみると,EC2, VPC などのリソースがこのスタックに紐付いていることがわかる.

スタックを削除

これにて,第一回のハンズオンで説明すべき事柄はすべて完了した. 最後に,使わなくなったスタックを削除しよう. スタックの削除には,二つの方法がある.

一つ目の方法は,前節の Cloudformation のコンソール画面で, "Delete" ボタンを押すことである (figure_title). すると,スタックの状態が "DELETE_IN_PROGRESS" に変わり,削除が完了すると CloudFormation のスタックの一覧から消える.

CloudFormationコンソール画面から,スタックを削除

二つ目の方法は,コマンドラインから行う方法である. 先ほど,デプロイを行ったコマンドラインに戻ろう. そうしたら,次のコマンドを実行する.

sh
$ cdk destroy
$ cdk destroy

このコマンドを実行すると,スタックの削除が始まる. 削除した後は,VPC, EC2 など,すべて跡形もなく消え去っていることを自身で確かめよう. CloudFormation を用いることで関連するすべての AWS リソースを一度に管理・削除することができるので,大変便利である.

スタックの削除は各自で必ず行うこと! 行わなかった場合, EC2 インスタンスの料金が発生し続けることになる!

また,本ハンズオンのために作成した SSH 鍵ペアも不要なので,削除しておく. まず, EC2 側に登録してある公開鍵を削除する. これも,コンソールおよびコマンドラインの二つの方法で実行できる.

コンソールから実行するには, EC2 の画面に行き,左のサイドバーの Key Pairs を選択する. 鍵の一覧が表示されるので, HirakeGoma とある鍵にチェックを入れ,画面右上の Actions から, Delete を実行する (figure_title).

EC2でSSH鍵ペアを削除

コマンドラインから実行するには,次のコマンドを使う.

sh
$ aws ec2 delete-key-pair --key-name "HirakeGoma"
$ aws ec2 delete-key-pair --key-name "HirakeGoma"

最後に,ローカルのコンピュータから鍵を削除する.

sh
$ rm -f ~/.ssh/HirakeGoma.pem
$ rm -f ~/.ssh/HirakeGoma.pem

これで,クラウドの片付けもすべて終了だ.

なお,頻繁に EC2 インスタンスを起動したりする場合は,いちいち SSH 鍵を削除する必要はない.

小括

ここまでが,本書の第一部の内容である. 盛りだくさんの内容であったが,ついてこれたであろうか?

(#chap_cloud_basics) では,クラウドの定義と用語の説明を行ったあと,なぜクラウドを使うのか,という点を議論した. 続いて (#sec_aws_general_introduction) では,クラウドを学ぶ具体的なプラットフォームとして AWS を取り上げ, AWS を使用するにあたり最低限必要な知識と用語の説明を行った. さらに, Hands-on #1: 初めての EC2 インスタンスを起動する のハンズオンでは AWS CLI と AWS CDK を使って,自身のプライベートなサーバーを AWS 上に立ち上げる演習を行った.

これらを通じて,いかに簡単に (たった数行のコマンドで!) 仮想サーバーを立ち上げたり,削除したりすることができるか,体験できただろう. 筆者は, (#chap_cloud_basics) でクラウドの最も重要な側面はダイナミックに計算リソースを拡大・縮小できることである,と述べた. この言葉の意味が,ハンズオンを通じてより明らかになっただろうか? ここで学んだ技術を少し応用するだけで,自分のウェブページをホストする仮想サーバーを作成したり,大量のコアを搭載した EC2 インスタンスを用意して科学計算を実行するなど,いろいろなアプリケーションが実現できる.

次章からは,今回学んだクラウドの技術を基に,より現実に即した問題を解くことを体験してもらう. お楽しみに!

]]>
Hands-on #1: 初めての EC2 インスタンスを起動する

ハンズオンの第一回では, CDK を使って EC2 のインスタンス(仮想サーバー)を作成し,SSH でサーバーにログインする,という演習を行う. このハンズオンを終えれば,あなたは自分だけのサーバーを AWS 上に立ち上げ,自由に計算を走らせることができるようになるのである!

準備

ハンズオンのソースコードは GitHub の handson/ec2-get-started に置いてある.

このハンズオンは,基本的に AWS の無料枠 の範囲内で実行することができる.

まずは,ハンズオンを実行するための環境を整える. これらの環境整備は,後のハンズオンでも前提となるものなので確実にミスなく行っていただきたい.

  • AWS Account: ハンズオンを実行するには個人の AWS アカウントが必要である. AWS アカウントの取得については (#sec:create_aws_account) を参照のこと.

  • Python と Node.js: 本ハンズオンを実行するには,Python (3.6 以上),Node.js (12.0 以上) がインストールされていなければならない.

  • AWS CLI: AWS CLI のインストールについては, (#aws_cli_install) を参照. ここに記載されている認証鍵の設定も済ませておくこと.

  • AWS CDK: AWS CDK のインストールについては, (#aws_cdk_install) を参照.

  • ソースコードのダウンロード: 本ハンズオンで使用するプログラムのソースコードを,以下のコマンドを使って GitHub からダウンロードする.

sh
$ git clone https://github.com/tomomano/learn-aws-by-coding.git
$ git clone https://github.com/tomomano/learn-aws-by-coding.git

あるいは, https://github.com/tomomano/learn-aws-by-coding のページに行って,右上のダウンロードボタンからダウンロードすることもできる.

Docker を使用する場合

Python, Node.js, AWS CDK など,ハンズオンのプログラムを実行するために必要なプログラム/ライブラリがインストール済みの Docker image を用意した. また,ハンズオンのソースコードもパッケージ済みである. Docker の使い方を知っている読者は,これを使えば,諸々のインストールをする必要なく,すぐにハンズオンのプログラムを実行できる.

使用方法については (#sec_handson_docker) を参照のこと.

SSH

SSH (secure shell) は Unix 系のリモートサーバーに安全にアクセスするためのツールである. 本ハンズオンでは, SSH を使って仮想サーバーにアクセスする. SSH に慣れていない読者のため,簡単な説明をここで行おう.

SSH による通信はすべて暗号化されているので,機密情報をインターネットを介して安全に送受信することができる. 本ハンズオンで,リモートのサーバーにアクセスするための SSH クライアントがローカルマシンにインストールされている必要がある. SSH クライアントは Linux/Mac には標準搭載されている. Windows の場合は WSL をインストールすることで SSH クライアントを利用することを推奨する ( (#environments) を参照).

SSH コマンドの基本的な使い方を次に示す. <host name> はアクセスする先のサーバーの IP アドレスや DNS によるホストネームが入る. <user name> は接続する先のユーザー名である.

sh
$ ssh <user name>@<host name>
$ ssh <user name>@<host name>

SSH は平文のパスワードによる認証を行うこともできるが,より強固なセキュリティを施すため,公開鍵暗号方式(Public Key Cryptography)による認証を行うことが強く推奨されており, EC2 はこの方法でしかアクセスを許していない. 公開鍵暗号方式の仕組みについては各自勉強してほしい. 本ハンズオンにおいて大事なことは,EC2 インスタンスが公開鍵(Public key)を保持し,クライアントとなるコンピュータ(読者自身のコンピュータ)が秘密鍵(Private key)を保持する,という点である. EC2 のインスタンスには秘密鍵を持ったコンピュータのみがアクセスすることができる.逆に言うと,秘密鍵が漏洩すると第三者もサーバーにアクセスできることになるので,秘密鍵は絶対に漏洩することのないよう注意して管理する

SSH コマンドでは,ログインのために使用する秘密鍵ファイルを -i もしくは --identity_file のオプションで指定することができる. たとえば,次のように使う.

sh
$ ssh -i Ec2SecretKey.pem <user name>@<host name>
$ ssh -i Ec2SecretKey.pem <user name>@<host name>

アプリケーションの説明

このハンズオンで作成するアプリケーションの概要を figure_title に示す.

ハンズオン#1で作製するアプリケーションのアーキテクチャ

このアプリケーションではまず,VPC (Virtual Private Cloud) を使ってプライベートな仮想ネットワーク環境を立ち上げている. その VPC の public subnet の内側に,EC2 (Elatic Compute Cloud) の仮想サーバーを配置する. さらに,セキュリティのため, Security Group による EC2 インスタンスへのアクセス制限を設定している. このようにして作成された仮想サーバーに,SSH を使ってアクセスし,簡単な計算を行う.

figure_title のようなアプリケーションを,CDK を使って構築する.

早速ではあるが,今回のハンズオンで使用するプログラムを見てみよう (handson/ec2-get-started/app.py).

python
class MyFirstEc2(core.Stack):

    def __init__(self, scope: core.App, name: str, key_name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        vpc = ec2.Vpc(
            self, "MyFirstEc2-Vpc",
            max_azs=1,
            cidr="10.10.0.0/23",
            subnet_configuration=[
                ec2.SubnetConfiguration(
                    name="public",
                    subnet_type=ec2.SubnetType.PUBLIC,
                )
            ],
            nat_gateways=0,
        )

        #
        sg = ec2.SecurityGroup(
            self, "MyFirstEc2Vpc-Sg",
            vpc=vpc,
            allow_all_outbound=True,
        )
        sg.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(22),
        )

        #
        host = ec2.Instance(
            self, "MyFirstEc2Instance",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ec2.MachineImage.latest_amazon_linux(),
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            security_group=sg,
            key_name=key_name
        )
class MyFirstEc2(core.Stack):

    def __init__(self, scope: core.App, name: str, key_name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        vpc = ec2.Vpc(
            self, "MyFirstEc2-Vpc",
            max_azs=1,
            cidr="10.10.0.0/23",
            subnet_configuration=[
                ec2.SubnetConfiguration(
                    name="public",
                    subnet_type=ec2.SubnetType.PUBLIC,
                )
            ],
            nat_gateways=0,
        )

        #
        sg = ec2.SecurityGroup(
            self, "MyFirstEc2Vpc-Sg",
            vpc=vpc,
            allow_all_outbound=True,
        )
        sg.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(22),
        )

        #
        host = ec2.Instance(
            self, "MyFirstEc2Instance",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ec2.MachineImage.latest_amazon_linux(),
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            security_group=sg,
            key_name=key_name
        )
  • まず最初に,VPC を定義する.

  • 次に, security group (SG) を定義している. ここでは,任意の IPv4 のアドレスからの,ポート 22 (SSH の接続に使用される)への接続を許可している. それ以外の接続は拒絶される.

  • 最後に,上記で作った VPC と SG が付与された EC2 インスタンスを作成している. インスタンスタイプは t2.micro を選択し, Amazon Linux を OS として設定している.

それぞれについて,もう少し詳しく説明しよう.

VPC (Virtual Private Cloud)

VPC のアイコン.

VPC

VPC は AWS 上にプライベートな仮想ネットワーク環境を構築するツールである.高度な計算システムを構築するには,複数のサーバーを連動させて計算を行う必要があるが,そのような場合に互いのアドレスなどを管理する必要があり,そういった目的で VPC は有用である.

本ハンズオンでは,サーバーは一つしか起動しないので,VPC の恩恵はよく分からないかもしれない.しかし,EC2 インスタンスは必ず VPC の中に配置されなければならない,という制約があるので,このハンズオンでもミニマルな VPC を構成している.

興味のある読者のために,VPC のコードについてもう少し詳しく説明しよう.

python
vpc = ec2.Vpc(
    self, "MyFirstEc2-Vpc",
    max_azs=1,
    cidr="10.10.0.0/23",
    subnet_configuration=[
        ec2.SubnetConfiguration(
            name="public",
            subnet_type=ec2.SubnetType.PUBLIC,
        )
    ],
    nat_gateways=0,
)
vpc = ec2.Vpc(
    self, "MyFirstEc2-Vpc",
    max_azs=1,
    cidr="10.10.0.0/23",
    subnet_configuration=[
        ec2.SubnetConfiguration(
            name="public",
            subnet_type=ec2.SubnetType.PUBLIC,
        )
    ],
    nat_gateways=0,
)
  • max_azs=1 : このパラメータは,前章で説明した avaialibility zone (AZ) を設定している. このハンズオンでは,特にデータセンターの障害などを気にする必要はないので 1 にしている.

  • cidr="10.10.0.0/23" : このパラメータは,VPC 内の IPv4 のレンジを指定している. CIDR 記法については, Wikipediaなどを参照. 10.10.0.0/2310.10.0.0 から 10.10.1.255 までの 512 個の連続したアドレス範囲を指している. つまり,この VPC では最大で 512 個のユニークな IPv4 アドレスが使えることになる. 今回はサーバーは一つなので 512 個は明らかに多すぎるが,VPC はアドレスの数はどれだけ作成しても無料なので,多めに作成した.

  • subnet_configuration=... : このパラメータは,VPC にどのようなサブネットを作るか,を決めている. サブネットの種類には private subnetpublic subnet の二種類がある. private subnet は基本的にインターネットとは遮断されたサブネット環境である. インターネットと繋がっていないので,セキュリティは極めて高く, VPC 内のサーバーとのみ通信を行えばよい EC2 インスタンスはここに配置する. Public subnet とはインターネットに繋がったサブネットである. 本ハンズオンで作成するサーバーは,外から SSH でログインを行いたいので, Public subnet 内に配置する. より詳細な記述は 公式ドキュメンテーション を参照.

  • natgateways=0 : これは少し高度な内容なので省略する (興味のある読者は 公式ドキュメンテーションを参照). が,これを 0 にしておかないと,NAT Gateway の利用料金が発生してしまうので,注意!

Security Group

Security group (SG) は, EC2 インスタンスに付与することのできる仮想ファイアーウォールである. たとえば,特定の IP アドレスから来た接続を許可・拒絶したり (インバウンド・トラフィックの制限) ,逆に特定の IP アドレスへのアクセスを禁止したり (アウトバウンド・トラフィックの制限) することができる.

コードの該当部分を見てみよう.

python
sg = ec2.SecurityGroup(
    self, "MyFirstEc2Vpc-Sg",
    vpc=vpc,
    allow_all_outbound=True,
)
sg.add_ingress_rule(
    peer=ec2.Peer.any_ipv4(),
    connection=ec2.Port.tcp(22),
)
sg = ec2.SecurityGroup(
    self, "MyFirstEc2Vpc-Sg",
    vpc=vpc,
    allow_all_outbound=True,
)
sg.add_ingress_rule(
    peer=ec2.Peer.any_ipv4(),
    connection=ec2.Port.tcp(22),
)

本ハンズオンでは, SSH による外部からの接続を許容するため, sg.add_ingress_rule(peer=ec2.Peer.any_ipv4(), connection=ec2.Port.tcp(22)) により,すべての IPv4 アドレスからのポート 22 番へのアクセスを許容している. また, SSH で EC2 インスタンスにログインしたのち,インターネットからプログラムなどをダウンロードできるよう, allow_all_outbound=True のパラメータを設定している.

SSH はデフォルトでは 22 番ポートを使用するのが慣例である.

セキュリティ上の観点からは,SSH の接続は自宅や大学・職場など特定の地点からの接続のみを許す方が望ましい.

EC2 (Elastic Compute Cloud)

EC2 のアイコン.

EC2

EC2 は AWS 上に仮想サーバーを立ち上げるサービスである. 個々の起動状態にある仮想サーバーのことをインスタンス (instance) とよぶ (しかし,口語的なコミュニケーションにおいては,サーバーとインスタンスという言葉は相互互換的に用いられることが多い).

EC2 では用途に応じて様々なインスタンスタイプが提供されている. table_title に,代表的なインスタンスタイプの例を挙げる (執筆時点での情報). EC2 のインスタンスタイプのすべてのリストは 公式ドキュメンテーション "Amazon EC2 Instance Types" で見ることができる.

EC2 instance types

Instance vCPU Memory (GiB) Network bandwidth (Gbps) Price per hour ($)
t2.micro 1 1 - 0.0116
t2.small 1 2 - 0.023
t2.medium 2 4 - 0.0464
c5.24xlarge 96 192 25 4.08
c5n.18xlarge 72 192 100 3.888
x1e.16xlarge 64 1952 10 13.344

table_title からわかるように, CPU は 1 コアから 96 コアまで,メモリーは 1GB から 2TB 以上まで,ネットワーク帯域は最大で 100Gbps まで,幅広く選択することができる. また,時間あたりの料金は,CPU・メモリーの占有数にほぼ比例する形で増加する. EC2 はサーバーの起動時間を秒単位で記録しており,利用料金は使用時間に比例する形で決定される. 例えば, t2.medium のインスタンスを 10 時間起動した場合,0.0464 * 10 = 0.464 ドルの料金が発生する.

AWS には 無料利用枠 というものがあり, t2.micro であれば月に 750 時間までは無料で利用することができる.

table_title の価格は us-east-1 のものである. リージョンによって多少価格設定が異なる.

上記で t2.micro の $0.0116 / hour という金額は, On-demand インスタンスというタイプを選択した場合の価格である. EC2 ではほかに, Spot instance とよばれるインスタンスも存在しする. Spot instance は,AWS のデータセンターの負荷が増えた場合,ユーザーのプログラムが実行中であっても AWS の判断により強制シャットダウンされる,という不便さを抱えているのだが,その分大幅に安い料金設定になっている. AWS で一時的に生じた余剰な空き CPU をユーザーに割安で貸し出す,という発想である. 科学計算やウェブサーバーなどの用途でコストを削減する目的で, Spot Instance を活用する事例も多数報告されている.

EC2 インスタンスを定義しているコードの該当部分を見てみよう.

python
host = ec2.Instance(
    self, "MyFirstEc2Instance",
    instance_type=ec2.InstanceType("t2.micro"),
    machine_image=ec2.MachineImage.latest_amazon_linux(),
    vpc=vpc,
    vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
    security_group=sg,
    key_name=key_name
)
host = ec2.Instance(
    self, "MyFirstEc2Instance",
    instance_type=ec2.InstanceType("t2.micro"),
    machine_image=ec2.MachineImage.latest_amazon_linux(),
    vpc=vpc,
    vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
    security_group=sg,
    key_name=key_name
)

ここでは, t2.micro というインスタンスタイプを選択している. さらに, machine_image として, Amazon Linux を選択している (Machine image は OS と似た概念である. Machine image については, (#sec_jupyter_and_deep_learning) でより詳しく触れる). さらに,上で定義した VPC, SG をこのインスタンスに付与している.

以上が,今回使用するプログラムの簡単な解説であった. ミニマルな形のプログラムではあるが,仮想サーバーを作成するのに必要なステップがおわかりいただけただろうか?

プログラムを実行する

さて,ハンズオンのコードの理解ができたところで,プログラムを実際に実行してみよう.繰り返しになるが, 準備 での準備ができていることが前提である.

Python の依存ライブラリのインストール

まずは,Python の依存ライブラリをインストールする.以下では,Python のライブラリを管理するツールとして, venv を使用する.

まずは, handson/ec2-get-started のディレクトリに移動しよう.

sh
$ cd handson/ec2-get-started
$ cd handson/ec2-get-started

ディレクトリを移動したら, venv で新しい仮想環境を作成し,インストールを実行する.

sh
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

これで Python の環境構築は完了だ.

venv の簡単な説明は (#venv_quick_guide) に記述してある.

環境によっては pip ではなく pip3 あるいは python3 -m pip に置き換える必要がある.

AWS のシークレットキーをセットする

AWS CLI および AWS CDK を使うには, AWS のシークレットキーが設定されている必要がある. シークレットキーの発行については (#aws_secrets) を参照のこと. シークレットキーを発行したら, (#aws_cli_install) を参照し,コマンドラインの設定を行う.

手順をここに短く要約すると,一つ目の方法は AWS_ACCESS_KEY_ID などの環境変数を設定するやり方である. もう一つの方法は, ~/.aws/credentials に認証情報を保存しておく方式である. シークレットキーの設定は AWS CLI/CDK を使用するうえで共通のステップになるので,しっかりと理解しておくように.

SSH 鍵を生成

EC2 インスタンスには SSH を使ってログインする. EC2 インスタンスを作成するのに先行して,今回のハンズオンで専用に使う SSH の公開鍵・秘密鍵のペアを準備する必要がある.

次の AWS CLI コマンドにより, HirakeGoma という名前のついた鍵を生成する.

sh
$ export KEY_NAME="HirakeGoma"
$ aws ec2 create-key-pair --key-name ${KEY_NAME} --query 'KeyMaterial' --output text > ${KEY_NAME}.pem
$ export KEY_NAME="HirakeGoma"
$ aws ec2 create-key-pair --key-name ${KEY_NAME} --query 'KeyMaterial' --output text > ${KEY_NAME}.pem

このコマンドを実行すると,現在のディレクトリに HirakeGoma.pem というファイルが作成される.これが,サーバーにアクセスするための秘密鍵である. SSH でこの鍵を使うため, ~/.ssh/ のディレクトリに鍵を移動する. さらに,秘密鍵が書き換えられたり第三者に閲覧されないよう,ファイルのアクセス権限を 400 に設定する.

sh
$ mv HirakeGoma.pem ~/.ssh/
$ chmod 400 ~/.ssh/HirakeGoma.pem
$ mv HirakeGoma.pem ~/.ssh/
$ chmod 400 ~/.ssh/HirakeGoma.pem

デプロイを実行

これまでのステップで, EC2 インスタンスをデプロイするための準備が整った! 早速,次のコマンドによりアプリケーションを AWS にデプロイしよう. -c key_name="HirakeGoma" というオプションで,先ほど生成した HirakeGoma という名前の鍵を使うよう指定している.

sh
$ cdk deploy -c key_name="HirakeGoma"
$ cdk deploy -c key_name="HirakeGoma"

このコマンドを実行すると, VPC, EC2 などが AWS 上に展開される. そして,コマンドの出力の最後に figure_title のような出力が得られるはずである. 出力の中で InstancePublicIp に続く数字が,起動したインスタンスのパブリック IP アドレスである. IP アドレスはデプロイごとにランダムなアドレスが割り当てられる.

CDKデプロイ実行後の出力

SSH でログイン

早速,SSH  で接続してみよう.

sh
$ ssh -i ~/.ssh/HirakeGoma.pem ec2-user@<IP address>
$ ssh -i ~/.ssh/HirakeGoma.pem ec2-user@<IP address>

-i オプションで,先ほど生成した秘密鍵を指定している. EC2 インスタンスにはデフォルトで ec2-user という名前のユーザーが作られているので,それを使用する. 最後に, <IP address> の部分は自身が作成した EC2 インスタンスの IP アドレスで置き換える (12.345.678.9 など).

ログインに成功すると, figure_title のような画面が表示される. リモートのサーバーにログインしているので,プロンプトが [ec2-user@ip-10-10-1-217 ~]$ のようになっていることを確認しよう.

SSH で EC2 インスタンスにログイン

おめでとう!これで,めでたく AWS 上に EC2 仮想サーバーを起動し,リモートからアクセスできるようになった!

起動した EC2 インスタンスで遊んでみる

せっかく新しいインスタンスを起動したので,少し遊んでみよう.

ログインした EC2 インスタンスで,次のコマンドを実行してみよう. CPU の情報を取得することができる.

sh
$ cat /proc/cpuinfo

processor       : 0
vendor_id       : GenuineIntel
cpu family      : 6
model           : 63
model name      : Intel(R) Xeon(R) CPU E5-2676 v3 @ 2.40GHz
stepping        : 2
microcode       : 0x43
cpu MHz         : 2400.096
cache size      : 30720 KB
$ cat /proc/cpuinfo

processor       : 0
vendor_id       : GenuineIntel
cpu family      : 6
model           : 63
model name      : Intel(R) Xeon(R) CPU E5-2676 v3 @ 2.40GHz
stepping        : 2
microcode       : 0x43
cpu MHz         : 2400.096
cache size      : 30720 KB

次に,実行中のプロセスやメモリの消費を見てみよう.

bash
$  top -n 1

top - 09:29:19 up 43 min,  1 user,  load average: 0.00, 0.00, 0.00
Tasks:  76 total,   1 running,  51 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.3%us,  0.3%sy,  0.1%ni, 98.9%id,  0.2%wa,  0.0%hi,  0.0%si,  0.2%st
Mem:   1009140k total,   270760k used,   738380k free,    14340k buffers
Swap:        0k total,        0k used,        0k free,   185856k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
    1 root      20   0 19696 2596 2268 S  0.0  0.3   0:01.21 init
    2 root      20   0     0    0    0 S  0.0  0.0   0:00.00 kthreadd
    3 root      20   0     0    0    0 I  0.0  0.0   0:00.00 kworker/0:0
$  top -n 1

top - 09:29:19 up 43 min,  1 user,  load average: 0.00, 0.00, 0.00
Tasks:  76 total,   1 running,  51 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.3%us,  0.3%sy,  0.1%ni, 98.9%id,  0.2%wa,  0.0%hi,  0.0%si,  0.2%st
Mem:   1009140k total,   270760k used,   738380k free,    14340k buffers
Swap:        0k total,        0k used,        0k free,   185856k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
    1 root      20   0 19696 2596 2268 S  0.0  0.3   0:01.21 init
    2 root      20   0     0    0    0 S  0.0  0.0   0:00.00 kthreadd
    3 root      20   0     0    0    0 I  0.0  0.0   0:00.00 kworker/0:0

t2.micro インスタンスなので, 1009140k = 1GB のメモリーがあることがわかる.

今回起動したインスタンスには Python 2 はインストール済みだが, Python 3 は入っていない. Python 3.6 のインストールを行ってみよう. インストールは簡単である.

sh
$ sudo yum update -y
$ sudo yum install -y python36
$ sudo yum update -y
$ sudo yum install -y python36

インストールした Python を起動してみよう.

sh
$ python3
Python 3.6.10 (default, Feb 10 2020, 19:55:14)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
$ python3
Python 3.6.10 (default, Feb 10 2020, 19:55:14)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Python のインタープリタが起動した! Ctrl + D あるいは exit() と入力することで,インタープリタを閉じることができる.

さて,サーバーでのお遊びはこんなところにしておこう (興味があれば各自いろいろと試してみると良い) . 次のコマンドでログアウトする.

sh
$ exit
$ exit

AWS コンソールから確認

これまでは,すべてコマンドラインから EC2 に関連する操作を行ってきた. EC2 インスタンスの状態を確認したり,サーバーをシャットダウンするなどの操作は,AWS コンソールから実行することもできる. 軽くこれを紹介しよう.

まず,ウェブブラウザを開いて AWS コンソールにログインする. ログインしたら, Services から EC2 を検索(選択)する. 次に,左のサイドバーの Instances とページをたどる. すると, figure_title のような画面が得られるはずである. この画面で,自分のアカウントの管理下にあるインスタンスを確認できる. 同様に,VPC・SG についてもコンソールから確認できる.

EC2 コンソール画面

コンソール右上で,正しいリージョン (今回の場合は ap-northeast-1, Tokyo) が選択されているか,注意する!

前章で CloudFormation について触れたが,今回デプロイしたアプリケーションも,CloudFormation のスタックとして管理されている. スタック (stack) とは, AWS リソースの集合のことを指す. 今回の場合は, VPC/EC2/SG などがスタックの中に含まれている. コンソールで CloudFormation のページに行ってみよう (figure_title).

CloudFormation コンソール画面

"MyFirstEc2" という名前のスタックがあることが確認できる. クリックをして中身を見てみると,EC2, VPC などのリソースがこのスタックに紐付いていることがわかる.

スタックを削除

これにて,第一回のハンズオンで説明すべき事柄はすべて完了した. 最後に,使わなくなったスタックを削除しよう. スタックの削除には,二つの方法がある.

一つ目の方法は,前節の Cloudformation のコンソール画面で, "Delete" ボタンを押すことである (figure_title). すると,スタックの状態が "DELETE_IN_PROGRESS" に変わり,削除が完了すると CloudFormation のスタックの一覧から消える.

CloudFormationコンソール画面から,スタックを削除

二つ目の方法は,コマンドラインから行う方法である. 先ほど,デプロイを行ったコマンドラインに戻ろう. そうしたら,次のコマンドを実行する.

sh
$ cdk destroy
$ cdk destroy

このコマンドを実行すると,スタックの削除が始まる. 削除した後は,VPC, EC2 など,すべて跡形もなく消え去っていることを自身で確かめよう. CloudFormation を用いることで関連するすべての AWS リソースを一度に管理・削除することができるので,大変便利である.

スタックの削除は各自で必ず行うこと! 行わなかった場合, EC2 インスタンスの料金が発生し続けることになる!

また,本ハンズオンのために作成した SSH 鍵ペアも不要なので,削除しておく. まず, EC2 側に登録してある公開鍵を削除する. これも,コンソールおよびコマンドラインの二つの方法で実行できる.

コンソールから実行するには, EC2 の画面に行き,左のサイドバーの Key Pairs を選択する. 鍵の一覧が表示されるので, HirakeGoma とある鍵にチェックを入れ,画面右上の Actions から, Delete を実行する (figure_title).

EC2でSSH鍵ペアを削除

コマンドラインから実行するには,次のコマンドを使う.

sh
$ aws ec2 delete-key-pair --key-name "HirakeGoma"
$ aws ec2 delete-key-pair --key-name "HirakeGoma"

最後に,ローカルのコンピュータから鍵を削除する.

sh
$ rm -f ~/.ssh/HirakeGoma.pem
$ rm -f ~/.ssh/HirakeGoma.pem

これで,クラウドの片付けもすべて終了だ.

なお,頻繁に EC2 インスタンスを起動したりする場合は,いちいち SSH 鍵を削除する必要はない.

小括

ここまでが,本書の第一部の内容である. 盛りだくさんの内容であったが,ついてこれたであろうか?

(#chap_cloud_basics) では,クラウドの定義と用語の説明を行ったあと,なぜクラウドを使うのか,という点を議論した. 続いて (#sec_aws_general_introduction) では,クラウドを学ぶ具体的なプラットフォームとして AWS を取り上げ, AWS を使用するにあたり最低限必要な知識と用語の説明を行った. さらに, Hands-on #1: 初めての EC2 インスタンスを起動する のハンズオンでは AWS CLI と AWS CDK を使って,自身のプライベートなサーバーを AWS 上に立ち上げる演習を行った.

これらを通じて,いかに簡単に (たった数行のコマンドで!) 仮想サーバーを立ち上げたり,削除したりすることができるか,体験できただろう. 筆者は, (#chap_cloud_basics) でクラウドの最も重要な側面はダイナミックに計算リソースを拡大・縮小できることである,と述べた. この言葉の意味が,ハンズオンを通じてより明らかになっただろうか? ここで学んだ技術を少し応用するだけで,自分のウェブページをホストする仮想サーバーを作成したり,大量のコアを搭載した EC2 インスタンスを用意して科学計算を実行するなど,いろいろなアプリケーションが実現できる.

次章からは,今回学んだクラウドの技術を基に,より現実に即した問題を解くことを体験してもらう. お楽しみに!

]]>
<![CDATA[Hands-on #2: AWS でディープラーニングを実践 ]]> https://note.toshiki.dev/development/aws/handson-jupyter https://note.toshiki.dev/development/aws/handson-jupyter Thu, 01 Jul 2021 00:00:00 GMT Hands-on #2: AWS でディープラーニングを実践

準備

ハンズオン第二回では, GPU を搭載した EC2 インスタンスを起動し,深層学習モデルの学習と推論を実行する演習を行う.

ハンズオンのソースコードは GitHub の handson/mnist に置いてある.

本ハンズオンの実行には,第一回ハンズオンで説明した準備 ( (#handson_01_prep)) が整っていることを前提とする. それ以外に必要な準備はない.

初期状態の AWS アカウントでは, GPU 搭載の G タイプのインスタンスの起動上限が 0 になっていることがある. これを確認するには, AWS コンソールから EC2 の画面を開き,左のメニューから Limits を選択する. その中の Running On-Demand All G instances という数字が G インスタンスの起動上限を表している.

もし,これが 0 になっていた場合は, AWS の自動申請フォームから上限緩和のリクエストを送る必要がある. 詳しくは 公式ドキュメンテーション "Amazon EC2 service quotas" を参照のこと.

このハンズオンは, g4dn.xlarge タイプの EC2 インスタンスを使うので,東京 (ap-northeast-1) リージョンでは 0.71 $/hour のコストが発生する.

AWS Educate Starter Account を使用している読者へ: 執筆時点においては, Starter Account には GPU 搭載型インスタンスを起動できないという制限が設けられている. したがって, Starter Account のユーザーはこのハンズオンを実行することはできない. 興味のある読者は,制限のない一般アカウントを自分自身で取得する必要があることに注意.

アプリケーションの説明

このハンズオンで作成するアプリケーションの概要を figure_title に示す.

ハンズオン#2で作製するアプリケーションのアーキテクチャ

図の多くの部分が,第一回ハンズオンで作成したアプリケーションと共通していることに気がつくだろう. 少しの変更で,簡単にディープラーニングを走らせる環境を構築することができるのである!主な変更点は次の3点である.

  • GPU を搭載した g4dn.xlarge インスタンスタイプを使用

  • ディープラーニングに使うプログラムがあらかじめインストールされた DLAMI (後述) を使用

  • SSH にポートフォワーディングのオプションつけてサーバーに接続し,サーバーで起動している Jupyter Notebook (後述) を使ってプログラムを書いたり実行したりする

ハンズオンで使用するプログラムのコードをみてみよう handson/mnist/app.py). コードは第一回目とほとんど共通である.変更点のみ解説を行う.

python
class Ec2ForDl(core.Stack):

    def __init__(self, scope: core.App, name: str, key_name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        vpc = ec2.Vpc(
            self, "Ec2ForDl-Vpc",
            max_azs=1,
            cidr="10.10.0.0/23",
            subnet_configuration=[
                ec2.SubnetConfiguration(
                    name="public",
                    subnet_type=ec2.SubnetType.PUBLIC,
                )
            ],
            nat_gateways=0,
        )

        sg = ec2.SecurityGroup(
            self, "Ec2ForDl-Sg",
            vpc=vpc,
            allow_all_outbound=True,
        )
        sg.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(22),
        )

        host = ec2.Instance(
            self, "Ec2ForDl-Instance",
            instance_type=ec2.InstanceType("g4dn.xlarge"), #
            machine_image=ec2.MachineImage.generic_linux({
                "us-east-1": "ami-060f07284bb6f9faf",
                "ap-northeast-1": "ami-09c0c16fc46a29ed9"
            }), #
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            security_group=sg,
            key_name=key_name
        )
class Ec2ForDl(core.Stack):

    def __init__(self, scope: core.App, name: str, key_name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        vpc = ec2.Vpc(
            self, "Ec2ForDl-Vpc",
            max_azs=1,
            cidr="10.10.0.0/23",
            subnet_configuration=[
                ec2.SubnetConfiguration(
                    name="public",
                    subnet_type=ec2.SubnetType.PUBLIC,
                )
            ],
            nat_gateways=0,
        )

        sg = ec2.SecurityGroup(
            self, "Ec2ForDl-Sg",
            vpc=vpc,
            allow_all_outbound=True,
        )
        sg.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(22),
        )

        host = ec2.Instance(
            self, "Ec2ForDl-Instance",
            instance_type=ec2.InstanceType("g4dn.xlarge"), #
            machine_image=ec2.MachineImage.generic_linux({
                "us-east-1": "ami-060f07284bb6f9faf",
                "ap-northeast-1": "ami-09c0c16fc46a29ed9"
            }), #
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            security_group=sg,
            key_name=key_name
        )
  • ここで, g4dn.xlarge インスタンスタイプを選択している (第一回では, CPU のみの t2.micro だった). g4dn.xlarge のインスタンスタイプは, (#sec_scientific_computing) ですでに触れた通り, NVIDIA T4 と呼ばれる廉価版モデルの GPU を搭載したインスタンスである. CPU は 4 core, メインメモリーは 16GB が割り当てあられている.

  • ここでは,Deep Learning 用の諸々のソフトウェアがプリンストールされた AMI (Deep Learning Amazon Machine Image; DLAMI) を選択している (第一回では,Amazon Linux という AMI を使用していた). 使用する AMI の ID は リージョンごとに指定する必要があり,ここでは us-east-1ap-northeast-1 でそれぞれ定義している.

DLAMI という新しい概念が出てきたので,説明しよう.

AMI が us-east-1ap-northeast-1 でしか定義されていないので,提供されているコードはこの二つのリージョンのみでデプロイ可能である. もしほかのリージョンを利用したい場合は, AMI の ID を自身で検索し,コードに書き込む必要がある.

DLAMI (Deep Learning Amazon Machine Image)

AMI (Amazon Machine Image) とは,大まかには OS (Operating System) に相当する概念である. 当然のことながら, OS がなければコンピュータはなにもできないので,EC2 インスタンスを起動するときには必ずなにかの OS を"インストール"する必要がある. EC2 が起動したときにロードされる OS に相当するものが, AMI である. AMI には,たとえば Ubuntu などの Linux 系 OS に加えて,Windows Server を選択することもできる. また, EC2 での使用に最適化された Amazon Linux という AMI も提供されている.

しかしながら, AMI を単なる OS と理解するのは過剰な単純化である. AMI には,ベースとなる (空っぽの) OS を選択することもできるが,それに加えて,各種のプログラムがインストール済みの AMI も定義することができる. 必要なプログラムがインストールされている AMI を見つけることができれば,自身でインストールを行ったり環境設定したりする手間が大幅に省ける. 具体例を挙げると,ハンズオン第一回では EC2 インスタンスに Python 3.6 をインストールする例を示したが,そのような操作をインスタンスが起動するたびに行うのは手間である!

AMI は, AWS 公式のものに加えて,サードパーティから提供されているものもある. また,自分自身の AMI を作って登録することも可能である (参考). AMI は EC2 のコンソールから検索することが可能である. あるいは,AWS CLI を使って,次のコマンドでリストを取得することができる (参考).

sh
$ aws ec2 describe-images --owners amazon
$ aws ec2 describe-images --owners amazon

ディープラーニングで頻繁に使われるプログラムがあらかじめインストールしてある AMI が, DLAMI (Deep Learning AMI) である. DLAMI には TensorFlow, PyTorch などの人気の高いディープラーニングのフレームワーク・ライブラリがすでにインストールされているため, EC2 インスタンスを起動してすぐさまディープラーニングの計算を実行できる.

本ハンズオンでは, Amazon Linux 2 をベースにした DLAMI を使用する (AMI ID = ami-09c0c16fc46a29ed9.この AMI は ap-northeast-1 でしか使用できない点に注意). AWS CLI を使って,この AMI の詳細情報を取得してみよう.

sh
$ aws ec2 describe-images --owners amazon --image-ids "ami-09c0c16fc46a29ed9" --region ap-northeast-1
$ aws ec2 describe-images --owners amazon --image-ids "ami-09c0c16fc46a29ed9" --region ap-northeast-1

AMI ID = ami-09c0c16fc46a29ed9 の詳細情報

figure_title のような出力が得られるはずである.得られた出力から,この DLAMI には PyTorch のバージョン 1.4.0 と 1.5.0 がインストールされていることがわかる. この DLAMI を使って,早速ディープラーニングの計算を実行してみよう.

DLAMI には具体的には何がインストールされているのだろうか? 興味のある読者のために,簡単な解説をしよう (参考: 公式ドキュメンテーション "What Is the AWS Deep Learning AMI?").

最も low-level なレイヤーとしては, GPU ドライバー がインストールされている. GPU ドライバーなしには OS は GPU とコマンドのやり取りをすることができない. 次のレイヤーが CUDAcuDNN である. CUDA は, NVIDIA 社が開発した, GPU 上で汎用コンピューティングを行うための言語であり, C++ 言語を拡張したシンタックスを備える. cuDNN は CUDA で書かれたディープラーニングのライブラリであり,n 次元の畳み込みなどの演算が実装されている. ここまでが, "Base" とよばれるタイプの DLAMI の中身である.

これに加えて, "Conda" とよばれるタイプには, "Base" のプログラム基盤の上に, TensorFlowPyTorch などのライブラリがインストールされている. さらに, Anaconda による仮想環境を使うことによって, TensorFlow の環境・ PyTorch の環境・ MxNet の環境など,フレームワークを簡単に切り替えることができる (これについては,後のハンズオンで触れる). また, Jupyter Notebook もインストール済みである.

スタックのデプロイ

スタックの中身が理解できたところで,早速スタックをデプロイしてみよう.

デプロイの手順は,ハンズオン 1 とほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). それぞれのコマンドの意味を忘れてしまった場合は,ハンズオン 1 に戻って復習していただきたい. シークレットキーの設定も忘れずに ( (#aws_cli_install)).

sh
# プロジェクトのディレクトリに移動
$ cd handson/mnist

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# SSH鍵を生成
$ export KEY_NAME="HirakeGoma"
$ aws ec2 create-key-pair --key-name ${KEY_NAME} --query 'KeyMaterial' --output text > ${KEY_NAME}.pem
$ mv HirakeGoma.pem ~/.ssh/
$ chmod 400 ~/.ssh/HirakeGoma.pem

# デプロイを実行
$ cdk deploy -c key_name="HirakeGoma"
# プロジェクトのディレクトリに移動
$ cd handson/mnist

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# SSH鍵を生成
$ export KEY_NAME="HirakeGoma"
$ aws ec2 create-key-pair --key-name ${KEY_NAME} --query 'KeyMaterial' --output text > ${KEY_NAME}.pem
$ mv HirakeGoma.pem ~/.ssh/
$ chmod 400 ~/.ssh/HirakeGoma.pem

# デプロイを実行
$ cdk deploy -c key_name="HirakeGoma"

ハンズオン 1 で作成した SSH 鍵の削除を行わなかった場合は, SSH 鍵を改めて作成する必要はない. 逆に言うと,同じ名前の SSH がすでに存在する場合は,鍵生成のコマンドはエラーを出力する.

デプロイのコマンドが無事に実行されれば, figure_title のような出力が得られるはずである.AWS により割り振られた IP アドレス (InstancePublicIp に続く文字列) をメモしておこう.

CDKデプロイ実行後の出力

ログイン

早速,デプロイしたインスタンスに SSH でログインしてみよう. ここでは,この後で使う Jupyter Notebook に接続するため,ポートフォワーディング (port forwarding) のオプション (-L) をつけてログインする.

sh
$ ssh -i ~/.ssh/HirakeGoma.pem -L localhost:8931:localhost:8888 ec2-user@<IP address>
$ ssh -i ~/.ssh/HirakeGoma.pem -L localhost:8931:localhost:8888 ec2-user@<IP address>

ポートフォワーディングとは,クライアントマシンの特定のアドレスへの接続を, SSH の暗号化された通信を介して,リモートマシンの特定のアドレスへ転送する,という意味である. このコマンドの -L localhost:8931:localhost:8888 は,自分のローカルマシンの localhost:8931 へのアクセスを,リモートサーバーの localhost:8888 のアドレスに転送せよ,という意味である (: につづく数字は TCP/IP ポートの番号を意味している). リモートサーバーのポート 8888 には,後述する Jupyter Notebook が起動している. したがって,ローカルマシンの localhost:8931 にアクセスすることで,リモートサーバーの Jupyter Notebook にアクセスすることができるのである (figure_title). このような SSH による接続方式をトンネル接続とよぶ.

SSH のポートフォワーディングによる Jupyter Notebook へのアクセス

ポートフォワーディングのオプションで,ポートの番号 (:8931, :8888 など) には 1 から 65535 までの任意の整数を指定できる. しかし,たとえば ポート 22 (SSH) やポート 80 (HTTP) など,いくつかすでに使われているポート番号もあることに注意する. また, Jupyter Notebook はデフォルトではポート 8888 番を使用する. したがって,リモート側のポート番号は,8888 を使うのがよい.

SSH ログインコマンドの <IP address> 部分は自身のインスタンスの IP アドレスを代入することを忘れずに.

本書の提供している Docker を使ってデプロイを実行した人へ

SSH によるログインは, Docker の外 (すなわちクライアントマシン本体) から行わなければならない. なぜなら,Jupyter を開くウェブブラウザは Docker の外にあるからである.

その際,秘密鍵を Docker の外にもってこなければならない. 手っ取り早い方法は, cat ~/.ssh/HirakeGoma と打って,出力結果をコピーしてホストマシンのファイルに書き込む方法である. あるいは -v オプションをつけて,ファイルシステムをマウントしてもよい (詳しくは Docker 公式ドキュメンテーション "Use volumes" を参照).

SSH によるログインができたら,早速, GPU の状態を確認してみよう. 次のコマンドを実行する.

sh
$ nvidia-smi
$ nvidia-smi

figure_title のような出力が得られるはずである. 出力を見ると, Tesla T4 型の GPU が 1 台搭載されていることが確認できる. その他,GPU Driver や CUDA のバージョン, GPU の負荷・メモリー使用率などの情報を確認することができる.

nvidia-smi の出力

Jupyter Notebook の起動

Jupyter Notebook とは,インタラクティブに Python のプログラムを書いたり実行したりするためのツールである. Jupyter は GUI としてウェブブラウザを介してアクセスする形式をとっており,まるでノートを書くように,プロットやテーブルのデータも美しく表示することができる (figure_title). Python に慣れている読者は,きっと一度は使ったことがあるだろう.

Jupyter Notebook の画面

このハンズオンでは, Jupyter Notebook を使ってディープラーニングのプログラムをインタラクティブに実行していく. DLAMI には既に Jupyter がインストールされているので,特段の設定なしに使い始めることができる.

早速, Jupyter を起動しよう. SSH でログインした先の EC2 インスタンスで,次のコマンドを実行すればよい.

sh
$ cd ~ # go to home directory
$ jupyter notebook
$ cd ~ # go to home directory
$ jupyter notebook

このコマンドを実行すると, figure_title のような出力が確認できるだろう. この出力から,Jupyter のサーバーが EC2 インスタンスの localhost:8888 というアドレスに起動していることがわかる. また, localhost:8888 に続く ?token=XXXX は,アクセスに使うための一時的なトークンである.

Jupyter Notebook サーバーを起動

Jupyter Notebook を初回に起動するときは,起動に数分程度の時間がかかることがある. ほかの動作も起動直後は遅く,いくつかプログラムを走らせていくうちに俊敏に反応するようになってくる. これは, AWS の GPU 搭載型仮想マシンの運用方法に起因する現象だと考えられる.

先ほど,ポートフォワーディングのオプションをつけて SSH 接続をしているので, Jupyter の起動している localhost:8888 には,ローカルマシンの localhost:8931 からアクセスすることができる. したがって,ローカルマシンから Jupyter にアクセスするには,ウェブブラウザ (Chrome, FireFox など)から次のアドレスにアクセスすれば良い.

http://localhost:8931/?token=XXXX&lt;/programlisting&gt;
http://localhost:8931/?token=XXXX&lt;/programlisting&gt;

?token=XXXX の部分は,上で Jupyter を起動したときに発行されたトークンの値に置き換える.

上のアドレスにアクセスすると, Jupyter のホーム画面が起動するはずである (figure_title). これで, Jupyter の準備が整った!

Jupyter ホーム画面

Jupyter Notebook の使い方 (超簡易版)

  • Shift + Enter: セルを実行

  • Esc: Command mode に遷移

  • メニューバーの "+" ボタン または Command mode で A ⇒ セルを追加

  • メニューバーの "ハサミ" ボタン または Command mode で X ⇒ セルを削除

ショートカットの一覧などは Ventsislav Yordanov 氏によるブログ が参考になる.

PyTorch はじめの一歩

PyTorch は Facebook AI Research LAB (FAIR) が中心となって開発を進めている,オープンソースのディープラーニングのライブラリである. PyTorch は 有名な例で言えば Tesla 社の自動運転プロジェクトなどで使用されており,執筆時点において最も人気の高いディープラーニングライブラリの一つである. 本ハンズオンでは, PyTorch を使ってディープラーニングの実践を行う.

PyTorch の歴史のお話

Facebook は PyTorch のほかに Caffe2 とよばれるディープラーニングのフレームワークを開発していた (初代 Caffe は UC Berkley の博士課程学生だった Yangqing Jia によって創られた). Caffe2 は 2018 年に PyTorch プロジェクトに合併された.

また,2019 年 12 月,日本の Preferred Networks 社が開発していた Chainer も開発を終了し,PyTorch の開発チームと協業していくことが発表された (詳しくは プレスリリース を参照). PyTorch には,開発統合前から Chainer からインスパイアされた API がいくつもあり, Chainer の DNA は今も PyTorch に引き継がれているのである…!

本格的なディープラーニングの計算に移る前に, PyTorch ライブラリを使って, GPU で計算を行うとはどういうものか,その入り口に触れてみよう.

まずは,新しいノートブックを作成する. Jupyter のホーム画面の右上の "New" を押し,"conda_pytorch_p36" という環境を選択したうえで,新規ノートブックを作成する (figure_title). "conda_pytorch_p36" の仮想環境には, PyTorch がインストール済みである.

新規ノートブックの作成. "conda_pytorch_p36" の環境を選択する.

ここでは,次のようなプログラムを書いて,実行していく. (figure_title).

PyTorch始めの一歩

まずは, PyTorch をインポートする.さらに, GPU が使える環境にあるか,確認する.

python
import torch
print("Is CUDA ready?", torch.cuda.is_available())
import torch
print("Is CUDA ready?", torch.cuda.is_available())

出力:

Is CUDA ready? True</programlisting>

次に,3x3 のランダムな行列を CPU 上に作ってみよう.

python
x = torch.rand(3,3)
print(x)
x = torch.rand(3,3)
print(x)

出力:

tensor([[0.6896, 0.2428, 0.3269], [0.0533, 0.3594, 0.9499], [0.9764, 0.5881, 0.0203]])</programlisting>

次に,行列を GPU 上に作成する.

python
y = torch.ones_like(x, device="cuda")
x = x.to("cuda")
y = torch.ones_like(x, device="cuda")
x = x.to("cuda")

そして,行列 xy の加算を,GPU 上で実行する

python
z = x + y
print(z)
z = x + y
print(z)

出力:

tensor([[1.6896, 1.2428, 1.3269], [1.0533, 1.3594, 1.9499], [1.9764, 1.5881, 1.0203]], device='cuda:0')</programlisting>

最後に, GPU 上にある行列を, CPU に戻す.

python
z = z.to("cpu")
print(z)
z = z.to("cpu")
print(z)

出力:

tensor([[1.6896, 1.2428, 1.3269], [1.0533, 1.3594, 1.9499], [1.9764, 1.5881, 1.0203]])</programlisting>

以上の例は, GPU を使った計算の初歩の初歩であるが,雰囲気はつかめただろうか? CPU と GPU で明示的にデータを交換するのが肝である. この例はたった 3x3 の行列の足し算なので, GPU を使う意味はまったくないが,これが数千,数万のサイズの行列になったとき, GPU は格段の威力を発揮する.

完成した Jupyter Notebook は /handson/mnist/pytorch/pytorch_get_started.ipynb にある. Jupyter の画面右上の "Upload" からこのファイルをアップロードして,コードを走らせることが可能である.

しなしながら,勉強のときにはコードはすべて自分の手で打つことが,記憶に残りやすくより効果的である,というのが筆者の意見である.

実際にベンチマークを取ることで GPU と CPU の速度を比較をしてみよう. 実行時間を計測するツールとして, Jupyter の提供する %time マジックコマンドを利用する.

まずは CPU を使用して,10000x10000 の行列の行列積を計算した場合の速度を測ってみよう. 先ほどのノートブックの続きに,次のコードを実行する.

python
s = 10000
device = "cpu"
x = torch.rand(s, s, device=device, dtype=torch.float32)
y = torch.rand(s, s, device=device, dtype=torch.float32)

%time z = torch.matmul(x,y)
s = 10000
device = "cpu"
x = torch.rand(s, s, device=device, dtype=torch.float32)
y = torch.rand(s, s, device=device, dtype=torch.float32)

%time z = torch.matmul(x,y)

出力は以下のようなものが得られるだろう. これは,行列積の計算に実時間で 5.8 秒かかったことを意味する (実行のたびに計測される時間はばらつくことに留意).

CPU times: user 11.5 s, sys: 140 ms, total: 11.6 s Wall time: 5.8 s</programlisting>

次に, GPU を使用して,同じ演算を行った場合の速度を計測しよう.

python
s = 10000
device = "cuda"
x = torch.rand(s, s, device=device, dtype=torch.float32)
y = torch.rand(s, s, device=device, dtype=torch.float32)
torch.cuda.synchronize()

%time z = torch.matmul(x,y); torch.cuda.synchronize()
s = 10000
device = "cuda"
x = torch.rand(s, s, device=device, dtype=torch.float32)
y = torch.rand(s, s, device=device, dtype=torch.float32)
torch.cuda.synchronize()

%time z = torch.matmul(x,y); torch.cuda.synchronize()

出力は以下のようなものになるだろう. GPU では 553 ミリ秒 で計算を終えることができた!

CPU times: user 334 ms, sys: 220 ms, total: 554 ms Wall time: 553 ms</programlisting>

PyTorch において, GPU での演算は asynchronous (非同期) で実行される. その理由で,上のベンチマークコードでは, torch.cuda.synchronize() というステートメントを埋め込んである.

このベンチマークでは, dtype=torch.float32 と指定することで,32bit の浮動小数点型を用いている. ディープラーニングの学習および推論の計算には,32bit 型,場合によっては 16bit 型が使われるのが一般的である. これの主な理由として,教師データやミニバッチに起因するノイズが,浮動小数点の精度よりも大きいことがあげられる. 32bit/16bit を採用することで,メモリー消費を抑えたり,計算速度の向上が達成できる.

上記のベンチマークから,GPU を用いることで,約 10 倍のスピードアップを実現することができた. スピードアップの性能は,演算の種類や行列のサイズに依存する. 行列積は,そのなかでも最も速度向上が見込まれる演算の一つである.

実践ディープラーニング! MNIST 手書き数字認識タスク

ここまで,AWS 上でディープラーニングの計算をするための概念や前提知識をながながと説明してきたが,ついにここからディープラーニングの計算を実際に走らせてみる.

ここでは,機械学習のタスクで最も初歩的かつ有名な MNIST データセットを使った数字認識を扱う (figure_title). これは,0 から 9 までの手書きの数字の画像が与えられ,その数字が何の数字なのかを当てる,というシンプルなタスクである.

MNIST 手書き数字データセット

今回は, MNIST 文字認識タスクを,畳み込みニューラルネットワーク (Convolutional Neural Network; CNN) を使って解く. ソースコードは /handson/minist/pytorch/ にある mnist.ipynbsimple_mnist.py である. なお,このプログラムは, PyTorch の公式 Example Project 集 を参考に,多少の改変を行ったものである.

まずは,カスタムのクラスや関数が定義された simple_mnist.py をアップロードしよう (figure_title). 画面右上の "Upload" ボタンをクリックし,ファイルを選択することでアップロードができる. この Python プログラムの中に,CNN のモデルや,学習の各イテレーションにおけるパラメータの更新などが記述されている. 今回はこの中身を説明することはしないが,興味のある読者は自身でソースコードを読んでみるとよい.

 をアップロード

simple_mnist.py をアップロードできたら,次に新しい notebook を作成しよう. "conda_pytorch_p36" の環境を選択することを忘れずに.

新しいノートブックが起動したら,まずは必要なライブラリをインポートしよう.

python
import torch
import torch.optim as optim
import torchvision
from torchvision import datasets, transforms
from matplotlib import pyplot as plt

# custom functions and classes
from simple_mnist import Model, train, evaluate
import torch
import torch.optim as optim
import torchvision
from torchvision import datasets, transforms
from matplotlib import pyplot as plt

# custom functions and classes
from simple_mnist import Model, train, evaluate

torchvision パッケージには,MNIST データセットをロードするなどの便利な関数が含まれている. また,今回のハンズオンで使うカスタムのクラス・関数 (Model, train, evaluate) のインポートを行っている.

次に,MNIST テストデータをダウンロードしよう. 同時に,画像データの輝度の正規化も行っている.

python
transf = transforms.Compose([transforms.ToTensor(),
                             transforms.Normalize((0.1307,), (0.3081,))])

trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transf)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)

testset = datasets.MNIST(root='./data', train=False, download=True, transform=transf)
testloader = torch.utils.data.DataLoader(testset, batch_size=1000, shuffle=True)
transf = transforms.Compose([transforms.ToTensor(),
                             transforms.Normalize((0.1307,), (0.3081,))])

trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transf)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)

testset = datasets.MNIST(root='./data', train=False, download=True, transform=transf)
testloader = torch.utils.data.DataLoader(testset, batch_size=1000, shuffle=True)

今回扱う MNIST データは 28x28 ピクセルの正方形の画像(モノクロ)と,それぞれのラベル(0 - 9 の数字)の組で構成されている. いくつかのデータを抽出して,可視化してみよう. figure_title のような出力が得られるはずである.

python
examples = iter(testloader)
example_data, example_targets = examples.next()

print("Example data size:", example_data.shape)

fig = plt.figure(figsize=(10,4))
for i in range(10):
    plt.subplot(2,5,i+1)
    plt.tight_layout()
    plt.imshow(example_data[i][0], cmap='gray', interpolation='none')
    plt.title("Ground Truth: {}".format(example_targets[i]))
    plt.xticks([])
    plt.yticks([])
plt.show()
examples = iter(testloader)
example_data, example_targets = examples.next()

print("Example data size:", example_data.shape)

fig = plt.figure(figsize=(10,4))
for i in range(10):
    plt.subplot(2,5,i+1)
    plt.tight_layout()
    plt.imshow(example_data[i][0], cmap='gray', interpolation='none')
    plt.title("Ground Truth: {}".format(example_targets[i]))
    plt.xticks([])
    plt.yticks([])
plt.show()

MNIST の手書き数字画像とその教師ラベル

次に, CNN のモデルを定義する.

python
model = Model()
model.to("cuda") # load to GPU
model = Model()
model.to("cuda") # load to GPU

今回使う Modelsimple_mnist.py の中で定義されている. このモデルは,figure_title に示したような,2層の畳み込み層と 2 層の全結合層からなるネットワークである. 出力層 (output layer) には Softmax 関数を使用し,損失関数 (Loss function) には 負の対数尤度関数 (Negative log likelyhood; NLL) を使用している.

本ハンズオンで使用するニューラルネットの構造.

続いて, CNN のパラメータを更新する最適化アルゴリズムを定義する. ここでは, 確率的勾配降下法 (Stochastic Gradient Descent; SGD) を使用している.

python
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)

これで,準備が整った. CNN の学習ループを開始しよう!

python
train_losses = []
for epoch in range(5):
    losses = train(model, trainloader, optimizer, epoch)
    train_losses = train_losses + losses
    test_loss, test_accuracy = evaluate(model, testloader)
    print(f"\nTest set: Average loss: {test_loss:.4f}, Accuracy: {test_accuracy:.1f}%\n")

plt.figure(figsize=(7,5))
plt.plot(train_losses)
plt.xlabel("Iterations")
plt.ylabel("Train loss")
plt.show()
train_losses = []
for epoch in range(5):
    losses = train(model, trainloader, optimizer, epoch)
    train_losses = train_losses + losses
    test_loss, test_accuracy = evaluate(model, testloader)
    print(f"\nTest set: Average loss: {test_loss:.4f}, Accuracy: {test_accuracy:.1f}%\n")

plt.figure(figsize=(7,5))
plt.plot(train_losses)
plt.xlabel("Iterations")
plt.ylabel("Train loss")
plt.show()

ここでは 5 エポック分の学習を行っている. GPU を使えば,これくらいの計算であれば 1 分程度で完了するだろう.

出力として, figure_title のようなプロットが得られるはずである. イテレーションを重ねるにつれて,損失関数 (Loss function) の値が減少している (=精度が向上している) ことがわかる.

学習の進行に対する Train loss の変化

出力にはテキスト形式で各エポック終了後のテストデータに対する精度も表示されている. 最終的には 98% 以上の極めて高い精度を実現できていることが確認できるだろう (figure_title).

学習したCNNのテストデータに対するスコア (5エポック後)

学習した CNN の推論結果を可視化してみよう. 次のコードを実行することで, figure_title のような出力が得られるだろう. この図で,下段右から二番目は,"1"に近い見た目をしているが,きちんと"9"と推論できている. なかなか賢い CNN を作り出すことができたようだ!

python
model.eval()

with torch.no_grad():
    output = model(example_data.to("cuda"))

fig = plt.figure(figsize=(10,4))
for i in range(10):
    plt.subplot(2,5,i+1)
    plt.tight_layout()
    plt.imshow(example_data[i][0], cmap='gray', interpolation='none')
    plt.title("Prediction: {}".format(output.data.max(1, keepdim=True)[1][i].item()))
    plt.xticks([])
    plt.yticks([])
plt.show()
model.eval()

with torch.no_grad():
    output = model(example_data.to("cuda"))

fig = plt.figure(figsize=(10,4))
for i in range(10):
    plt.subplot(2,5,i+1)
    plt.tight_layout()
    plt.imshow(example_data[i][0], cmap='gray', interpolation='none')
    plt.title("Prediction: {}".format(output.data.max(1, keepdim=True)[1][i].item()))
    plt.xticks([])
    plt.yticks([])
plt.show()

学習した CNN による,MNIST画像の推論結果

最後に,学習したニューラルネットワークのパラメータを mnist_cnn.pt というファイル名で保存しておこう. これで,将来いつでも今回学習したモデルを再現し,別の実験に使用することができる.

python
torch.save(model.state_dict(), "mnist_cnn.pt")
torch.save(model.state_dict(), "mnist_cnn.pt")

以上が, AWS クラウドの仮想サーバーを立ち上げ,最初のディープラーニングの計算を行う一連の流れである. MNIST 文字認識のタスクを行うニューラルネットを,クラウド上の GPU を使って高速に学習させ,現実的な問題を一つ解くことができたのである. 興味のある読者は,今回のハンズオンを雛形に,自分の所望の計算を走らせてみるとよいだろう.

スタックの削除

これにて,ハンズオン第二回の内容はすべて説明した. クラウドの利用料金を最小化するため,使い終わった EC2 インスタンスはすぐさま削除しよう.

ハンズオン第一回と同様に, AWS の CloudFormation コンソールか, AWS CLI により削除を実行する (詳細は (#handson_01_delete_stack) 参照).

sh
$ cdk destroy
$ cdk destroy

スタックの削除は各自で必ず行うこと! 行わなかった場合,EC2 インスタンスの料金が発生し続けることになる! g4dn.xlarge は $0.71 / hour の料金設定なので,一日起動しつづけると約$17 の請求が発生することになる!

AWS のバジェットアラート

AWS の初心者が (あるいは経験者も) しばしば陥る失敗が,インスタンスの停止忘れなどで無駄なリソースがクラウドで放置されてしまい,巨大な額の請求が届く,というミスだ. 特に,開発を行っている間はこのような事態は起こりうるものだと思って,備えておかなければならない. このような事態を未然に防ぐため, AWS Budgets という機能が無料で提供されている. AWS Budgets を利用することで,月の利用金額がある閾値を超えた場合にユーザーにメールが送信される,などのアラートを設定することができる. 詳細な手順は AWS の公式ブログ "Getting Started with AWS Budgets" を参照のこと. 本書の読者も,ぜひこのタイミングでアラートを設定しておくことを推奨する.

]]>
Hands-on #2: AWS でディープラーニングを実践

準備

ハンズオン第二回では, GPU を搭載した EC2 インスタンスを起動し,深層学習モデルの学習と推論を実行する演習を行う.

ハンズオンのソースコードは GitHub の handson/mnist に置いてある.

本ハンズオンの実行には,第一回ハンズオンで説明した準備 ( (#handson_01_prep)) が整っていることを前提とする. それ以外に必要な準備はない.

初期状態の AWS アカウントでは, GPU 搭載の G タイプのインスタンスの起動上限が 0 になっていることがある. これを確認するには, AWS コンソールから EC2 の画面を開き,左のメニューから Limits を選択する. その中の Running On-Demand All G instances という数字が G インスタンスの起動上限を表している.

もし,これが 0 になっていた場合は, AWS の自動申請フォームから上限緩和のリクエストを送る必要がある. 詳しくは 公式ドキュメンテーション "Amazon EC2 service quotas" を参照のこと.

このハンズオンは, g4dn.xlarge タイプの EC2 インスタンスを使うので,東京 (ap-northeast-1) リージョンでは 0.71 $/hour のコストが発生する.

AWS Educate Starter Account を使用している読者へ: 執筆時点においては, Starter Account には GPU 搭載型インスタンスを起動できないという制限が設けられている. したがって, Starter Account のユーザーはこのハンズオンを実行することはできない. 興味のある読者は,制限のない一般アカウントを自分自身で取得する必要があることに注意.

アプリケーションの説明

このハンズオンで作成するアプリケーションの概要を figure_title に示す.

ハンズオン#2で作製するアプリケーションのアーキテクチャ

図の多くの部分が,第一回ハンズオンで作成したアプリケーションと共通していることに気がつくだろう. 少しの変更で,簡単にディープラーニングを走らせる環境を構築することができるのである!主な変更点は次の3点である.

  • GPU を搭載した g4dn.xlarge インスタンスタイプを使用

  • ディープラーニングに使うプログラムがあらかじめインストールされた DLAMI (後述) を使用

  • SSH にポートフォワーディングのオプションつけてサーバーに接続し,サーバーで起動している Jupyter Notebook (後述) を使ってプログラムを書いたり実行したりする

ハンズオンで使用するプログラムのコードをみてみよう handson/mnist/app.py). コードは第一回目とほとんど共通である.変更点のみ解説を行う.

python
class Ec2ForDl(core.Stack):

    def __init__(self, scope: core.App, name: str, key_name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        vpc = ec2.Vpc(
            self, "Ec2ForDl-Vpc",
            max_azs=1,
            cidr="10.10.0.0/23",
            subnet_configuration=[
                ec2.SubnetConfiguration(
                    name="public",
                    subnet_type=ec2.SubnetType.PUBLIC,
                )
            ],
            nat_gateways=0,
        )

        sg = ec2.SecurityGroup(
            self, "Ec2ForDl-Sg",
            vpc=vpc,
            allow_all_outbound=True,
        )
        sg.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(22),
        )

        host = ec2.Instance(
            self, "Ec2ForDl-Instance",
            instance_type=ec2.InstanceType("g4dn.xlarge"), #
            machine_image=ec2.MachineImage.generic_linux({
                "us-east-1": "ami-060f07284bb6f9faf",
                "ap-northeast-1": "ami-09c0c16fc46a29ed9"
            }), #
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            security_group=sg,
            key_name=key_name
        )
class Ec2ForDl(core.Stack):

    def __init__(self, scope: core.App, name: str, key_name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        vpc = ec2.Vpc(
            self, "Ec2ForDl-Vpc",
            max_azs=1,
            cidr="10.10.0.0/23",
            subnet_configuration=[
                ec2.SubnetConfiguration(
                    name="public",
                    subnet_type=ec2.SubnetType.PUBLIC,
                )
            ],
            nat_gateways=0,
        )

        sg = ec2.SecurityGroup(
            self, "Ec2ForDl-Sg",
            vpc=vpc,
            allow_all_outbound=True,
        )
        sg.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(22),
        )

        host = ec2.Instance(
            self, "Ec2ForDl-Instance",
            instance_type=ec2.InstanceType("g4dn.xlarge"), #
            machine_image=ec2.MachineImage.generic_linux({
                "us-east-1": "ami-060f07284bb6f9faf",
                "ap-northeast-1": "ami-09c0c16fc46a29ed9"
            }), #
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            security_group=sg,
            key_name=key_name
        )
  • ここで, g4dn.xlarge インスタンスタイプを選択している (第一回では, CPU のみの t2.micro だった). g4dn.xlarge のインスタンスタイプは, (#sec_scientific_computing) ですでに触れた通り, NVIDIA T4 と呼ばれる廉価版モデルの GPU を搭載したインスタンスである. CPU は 4 core, メインメモリーは 16GB が割り当てあられている.

  • ここでは,Deep Learning 用の諸々のソフトウェアがプリンストールされた AMI (Deep Learning Amazon Machine Image; DLAMI) を選択している (第一回では,Amazon Linux という AMI を使用していた). 使用する AMI の ID は リージョンごとに指定する必要があり,ここでは us-east-1ap-northeast-1 でそれぞれ定義している.

DLAMI という新しい概念が出てきたので,説明しよう.

AMI が us-east-1ap-northeast-1 でしか定義されていないので,提供されているコードはこの二つのリージョンのみでデプロイ可能である. もしほかのリージョンを利用したい場合は, AMI の ID を自身で検索し,コードに書き込む必要がある.

DLAMI (Deep Learning Amazon Machine Image)

AMI (Amazon Machine Image) とは,大まかには OS (Operating System) に相当する概念である. 当然のことながら, OS がなければコンピュータはなにもできないので,EC2 インスタンスを起動するときには必ずなにかの OS を"インストール"する必要がある. EC2 が起動したときにロードされる OS に相当するものが, AMI である. AMI には,たとえば Ubuntu などの Linux 系 OS に加えて,Windows Server を選択することもできる. また, EC2 での使用に最適化された Amazon Linux という AMI も提供されている.

しかしながら, AMI を単なる OS と理解するのは過剰な単純化である. AMI には,ベースとなる (空っぽの) OS を選択することもできるが,それに加えて,各種のプログラムがインストール済みの AMI も定義することができる. 必要なプログラムがインストールされている AMI を見つけることができれば,自身でインストールを行ったり環境設定したりする手間が大幅に省ける. 具体例を挙げると,ハンズオン第一回では EC2 インスタンスに Python 3.6 をインストールする例を示したが,そのような操作をインスタンスが起動するたびに行うのは手間である!

AMI は, AWS 公式のものに加えて,サードパーティから提供されているものもある. また,自分自身の AMI を作って登録することも可能である (参考). AMI は EC2 のコンソールから検索することが可能である. あるいは,AWS CLI を使って,次のコマンドでリストを取得することができる (参考).

sh
$ aws ec2 describe-images --owners amazon
$ aws ec2 describe-images --owners amazon

ディープラーニングで頻繁に使われるプログラムがあらかじめインストールしてある AMI が, DLAMI (Deep Learning AMI) である. DLAMI には TensorFlow, PyTorch などの人気の高いディープラーニングのフレームワーク・ライブラリがすでにインストールされているため, EC2 インスタンスを起動してすぐさまディープラーニングの計算を実行できる.

本ハンズオンでは, Amazon Linux 2 をベースにした DLAMI を使用する (AMI ID = ami-09c0c16fc46a29ed9.この AMI は ap-northeast-1 でしか使用できない点に注意). AWS CLI を使って,この AMI の詳細情報を取得してみよう.

sh
$ aws ec2 describe-images --owners amazon --image-ids "ami-09c0c16fc46a29ed9" --region ap-northeast-1
$ aws ec2 describe-images --owners amazon --image-ids "ami-09c0c16fc46a29ed9" --region ap-northeast-1

AMI ID = ami-09c0c16fc46a29ed9 の詳細情報

figure_title のような出力が得られるはずである.得られた出力から,この DLAMI には PyTorch のバージョン 1.4.0 と 1.5.0 がインストールされていることがわかる. この DLAMI を使って,早速ディープラーニングの計算を実行してみよう.

DLAMI には具体的には何がインストールされているのだろうか? 興味のある読者のために,簡単な解説をしよう (参考: 公式ドキュメンテーション "What Is the AWS Deep Learning AMI?").

最も low-level なレイヤーとしては, GPU ドライバー がインストールされている. GPU ドライバーなしには OS は GPU とコマンドのやり取りをすることができない. 次のレイヤーが CUDAcuDNN である. CUDA は, NVIDIA 社が開発した, GPU 上で汎用コンピューティングを行うための言語であり, C++ 言語を拡張したシンタックスを備える. cuDNN は CUDA で書かれたディープラーニングのライブラリであり,n 次元の畳み込みなどの演算が実装されている. ここまでが, "Base" とよばれるタイプの DLAMI の中身である.

これに加えて, "Conda" とよばれるタイプには, "Base" のプログラム基盤の上に, TensorFlowPyTorch などのライブラリがインストールされている. さらに, Anaconda による仮想環境を使うことによって, TensorFlow の環境・ PyTorch の環境・ MxNet の環境など,フレームワークを簡単に切り替えることができる (これについては,後のハンズオンで触れる). また, Jupyter Notebook もインストール済みである.

スタックのデプロイ

スタックの中身が理解できたところで,早速スタックをデプロイしてみよう.

デプロイの手順は,ハンズオン 1 とほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). それぞれのコマンドの意味を忘れてしまった場合は,ハンズオン 1 に戻って復習していただきたい. シークレットキーの設定も忘れずに ( (#aws_cli_install)).

sh
# プロジェクトのディレクトリに移動
$ cd handson/mnist

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# SSH鍵を生成
$ export KEY_NAME="HirakeGoma"
$ aws ec2 create-key-pair --key-name ${KEY_NAME} --query 'KeyMaterial' --output text > ${KEY_NAME}.pem
$ mv HirakeGoma.pem ~/.ssh/
$ chmod 400 ~/.ssh/HirakeGoma.pem

# デプロイを実行
$ cdk deploy -c key_name="HirakeGoma"
# プロジェクトのディレクトリに移動
$ cd handson/mnist

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# SSH鍵を生成
$ export KEY_NAME="HirakeGoma"
$ aws ec2 create-key-pair --key-name ${KEY_NAME} --query 'KeyMaterial' --output text > ${KEY_NAME}.pem
$ mv HirakeGoma.pem ~/.ssh/
$ chmod 400 ~/.ssh/HirakeGoma.pem

# デプロイを実行
$ cdk deploy -c key_name="HirakeGoma"

ハンズオン 1 で作成した SSH 鍵の削除を行わなかった場合は, SSH 鍵を改めて作成する必要はない. 逆に言うと,同じ名前の SSH がすでに存在する場合は,鍵生成のコマンドはエラーを出力する.

デプロイのコマンドが無事に実行されれば, figure_title のような出力が得られるはずである.AWS により割り振られた IP アドレス (InstancePublicIp に続く文字列) をメモしておこう.

CDKデプロイ実行後の出力

ログイン

早速,デプロイしたインスタンスに SSH でログインしてみよう. ここでは,この後で使う Jupyter Notebook に接続するため,ポートフォワーディング (port forwarding) のオプション (-L) をつけてログインする.

sh
$ ssh -i ~/.ssh/HirakeGoma.pem -L localhost:8931:localhost:8888 ec2-user@<IP address>
$ ssh -i ~/.ssh/HirakeGoma.pem -L localhost:8931:localhost:8888 ec2-user@<IP address>

ポートフォワーディングとは,クライアントマシンの特定のアドレスへの接続を, SSH の暗号化された通信を介して,リモートマシンの特定のアドレスへ転送する,という意味である. このコマンドの -L localhost:8931:localhost:8888 は,自分のローカルマシンの localhost:8931 へのアクセスを,リモートサーバーの localhost:8888 のアドレスに転送せよ,という意味である (: につづく数字は TCP/IP ポートの番号を意味している). リモートサーバーのポート 8888 には,後述する Jupyter Notebook が起動している. したがって,ローカルマシンの localhost:8931 にアクセスすることで,リモートサーバーの Jupyter Notebook にアクセスすることができるのである (figure_title). このような SSH による接続方式をトンネル接続とよぶ.

SSH のポートフォワーディングによる Jupyter Notebook へのアクセス

ポートフォワーディングのオプションで,ポートの番号 (:8931, :8888 など) には 1 から 65535 までの任意の整数を指定できる. しかし,たとえば ポート 22 (SSH) やポート 80 (HTTP) など,いくつかすでに使われているポート番号もあることに注意する. また, Jupyter Notebook はデフォルトではポート 8888 番を使用する. したがって,リモート側のポート番号は,8888 を使うのがよい.

SSH ログインコマンドの <IP address> 部分は自身のインスタンスの IP アドレスを代入することを忘れずに.

本書の提供している Docker を使ってデプロイを実行した人へ

SSH によるログインは, Docker の外 (すなわちクライアントマシン本体) から行わなければならない. なぜなら,Jupyter を開くウェブブラウザは Docker の外にあるからである.

その際,秘密鍵を Docker の外にもってこなければならない. 手っ取り早い方法は, cat ~/.ssh/HirakeGoma と打って,出力結果をコピーしてホストマシンのファイルに書き込む方法である. あるいは -v オプションをつけて,ファイルシステムをマウントしてもよい (詳しくは Docker 公式ドキュメンテーション "Use volumes" を参照).

SSH によるログインができたら,早速, GPU の状態を確認してみよう. 次のコマンドを実行する.

sh
$ nvidia-smi
$ nvidia-smi

figure_title のような出力が得られるはずである. 出力を見ると, Tesla T4 型の GPU が 1 台搭載されていることが確認できる. その他,GPU Driver や CUDA のバージョン, GPU の負荷・メモリー使用率などの情報を確認することができる.

nvidia-smi の出力

Jupyter Notebook の起動

Jupyter Notebook とは,インタラクティブに Python のプログラムを書いたり実行したりするためのツールである. Jupyter は GUI としてウェブブラウザを介してアクセスする形式をとっており,まるでノートを書くように,プロットやテーブルのデータも美しく表示することができる (figure_title). Python に慣れている読者は,きっと一度は使ったことがあるだろう.

Jupyter Notebook の画面

このハンズオンでは, Jupyter Notebook を使ってディープラーニングのプログラムをインタラクティブに実行していく. DLAMI には既に Jupyter がインストールされているので,特段の設定なしに使い始めることができる.

早速, Jupyter を起動しよう. SSH でログインした先の EC2 インスタンスで,次のコマンドを実行すればよい.

sh
$ cd ~ # go to home directory
$ jupyter notebook
$ cd ~ # go to home directory
$ jupyter notebook

このコマンドを実行すると, figure_title のような出力が確認できるだろう. この出力から,Jupyter のサーバーが EC2 インスタンスの localhost:8888 というアドレスに起動していることがわかる. また, localhost:8888 に続く ?token=XXXX は,アクセスに使うための一時的なトークンである.

Jupyter Notebook サーバーを起動

Jupyter Notebook を初回に起動するときは,起動に数分程度の時間がかかることがある. ほかの動作も起動直後は遅く,いくつかプログラムを走らせていくうちに俊敏に反応するようになってくる. これは, AWS の GPU 搭載型仮想マシンの運用方法に起因する現象だと考えられる.

先ほど,ポートフォワーディングのオプションをつけて SSH 接続をしているので, Jupyter の起動している localhost:8888 には,ローカルマシンの localhost:8931 からアクセスすることができる. したがって,ローカルマシンから Jupyter にアクセスするには,ウェブブラウザ (Chrome, FireFox など)から次のアドレスにアクセスすれば良い.

http://localhost:8931/?token=XXXX&lt;/programlisting&gt;
http://localhost:8931/?token=XXXX&lt;/programlisting&gt;

?token=XXXX の部分は,上で Jupyter を起動したときに発行されたトークンの値に置き換える.

上のアドレスにアクセスすると, Jupyter のホーム画面が起動するはずである (figure_title). これで, Jupyter の準備が整った!

Jupyter ホーム画面

Jupyter Notebook の使い方 (超簡易版)

  • Shift + Enter: セルを実行

  • Esc: Command mode に遷移

  • メニューバーの "+" ボタン または Command mode で A ⇒ セルを追加

  • メニューバーの "ハサミ" ボタン または Command mode で X ⇒ セルを削除

ショートカットの一覧などは Ventsislav Yordanov 氏によるブログ が参考になる.

PyTorch はじめの一歩

PyTorch は Facebook AI Research LAB (FAIR) が中心となって開発を進めている,オープンソースのディープラーニングのライブラリである. PyTorch は 有名な例で言えば Tesla 社の自動運転プロジェクトなどで使用されており,執筆時点において最も人気の高いディープラーニングライブラリの一つである. 本ハンズオンでは, PyTorch を使ってディープラーニングの実践を行う.

PyTorch の歴史のお話

Facebook は PyTorch のほかに Caffe2 とよばれるディープラーニングのフレームワークを開発していた (初代 Caffe は UC Berkley の博士課程学生だった Yangqing Jia によって創られた). Caffe2 は 2018 年に PyTorch プロジェクトに合併された.

また,2019 年 12 月,日本の Preferred Networks 社が開発していた Chainer も開発を終了し,PyTorch の開発チームと協業していくことが発表された (詳しくは プレスリリース を参照). PyTorch には,開発統合前から Chainer からインスパイアされた API がいくつもあり, Chainer の DNA は今も PyTorch に引き継がれているのである…!

本格的なディープラーニングの計算に移る前に, PyTorch ライブラリを使って, GPU で計算を行うとはどういうものか,その入り口に触れてみよう.

まずは,新しいノートブックを作成する. Jupyter のホーム画面の右上の "New" を押し,"conda_pytorch_p36" という環境を選択したうえで,新規ノートブックを作成する (figure_title). "conda_pytorch_p36" の仮想環境には, PyTorch がインストール済みである.

新規ノートブックの作成. "conda_pytorch_p36" の環境を選択する.

ここでは,次のようなプログラムを書いて,実行していく. (figure_title).

PyTorch始めの一歩

まずは, PyTorch をインポートする.さらに, GPU が使える環境にあるか,確認する.

python
import torch
print("Is CUDA ready?", torch.cuda.is_available())
import torch
print("Is CUDA ready?", torch.cuda.is_available())

出力:

Is CUDA ready? True</programlisting>

次に,3x3 のランダムな行列を CPU 上に作ってみよう.

python
x = torch.rand(3,3)
print(x)
x = torch.rand(3,3)
print(x)

出力:

tensor([[0.6896, 0.2428, 0.3269], [0.0533, 0.3594, 0.9499], [0.9764, 0.5881, 0.0203]])</programlisting>

次に,行列を GPU 上に作成する.

python
y = torch.ones_like(x, device="cuda")
x = x.to("cuda")
y = torch.ones_like(x, device="cuda")
x = x.to("cuda")

そして,行列 xy の加算を,GPU 上で実行する

python
z = x + y
print(z)
z = x + y
print(z)

出力:

tensor([[1.6896, 1.2428, 1.3269], [1.0533, 1.3594, 1.9499], [1.9764, 1.5881, 1.0203]], device='cuda:0')</programlisting>

最後に, GPU 上にある行列を, CPU に戻す.

python
z = z.to("cpu")
print(z)
z = z.to("cpu")
print(z)

出力:

tensor([[1.6896, 1.2428, 1.3269], [1.0533, 1.3594, 1.9499], [1.9764, 1.5881, 1.0203]])</programlisting>

以上の例は, GPU を使った計算の初歩の初歩であるが,雰囲気はつかめただろうか? CPU と GPU で明示的にデータを交換するのが肝である. この例はたった 3x3 の行列の足し算なので, GPU を使う意味はまったくないが,これが数千,数万のサイズの行列になったとき, GPU は格段の威力を発揮する.

完成した Jupyter Notebook は /handson/mnist/pytorch/pytorch_get_started.ipynb にある. Jupyter の画面右上の "Upload" からこのファイルをアップロードして,コードを走らせることが可能である.

しなしながら,勉強のときにはコードはすべて自分の手で打つことが,記憶に残りやすくより効果的である,というのが筆者の意見である.

実際にベンチマークを取ることで GPU と CPU の速度を比較をしてみよう. 実行時間を計測するツールとして, Jupyter の提供する %time マジックコマンドを利用する.

まずは CPU を使用して,10000x10000 の行列の行列積を計算した場合の速度を測ってみよう. 先ほどのノートブックの続きに,次のコードを実行する.

python
s = 10000
device = "cpu"
x = torch.rand(s, s, device=device, dtype=torch.float32)
y = torch.rand(s, s, device=device, dtype=torch.float32)

%time z = torch.matmul(x,y)
s = 10000
device = "cpu"
x = torch.rand(s, s, device=device, dtype=torch.float32)
y = torch.rand(s, s, device=device, dtype=torch.float32)

%time z = torch.matmul(x,y)

出力は以下のようなものが得られるだろう. これは,行列積の計算に実時間で 5.8 秒かかったことを意味する (実行のたびに計測される時間はばらつくことに留意).

CPU times: user 11.5 s, sys: 140 ms, total: 11.6 s Wall time: 5.8 s</programlisting>

次に, GPU を使用して,同じ演算を行った場合の速度を計測しよう.

python
s = 10000
device = "cuda"
x = torch.rand(s, s, device=device, dtype=torch.float32)
y = torch.rand(s, s, device=device, dtype=torch.float32)
torch.cuda.synchronize()

%time z = torch.matmul(x,y); torch.cuda.synchronize()
s = 10000
device = "cuda"
x = torch.rand(s, s, device=device, dtype=torch.float32)
y = torch.rand(s, s, device=device, dtype=torch.float32)
torch.cuda.synchronize()

%time z = torch.matmul(x,y); torch.cuda.synchronize()

出力は以下のようなものになるだろう. GPU では 553 ミリ秒 で計算を終えることができた!

CPU times: user 334 ms, sys: 220 ms, total: 554 ms Wall time: 553 ms</programlisting>

PyTorch において, GPU での演算は asynchronous (非同期) で実行される. その理由で,上のベンチマークコードでは, torch.cuda.synchronize() というステートメントを埋め込んである.

このベンチマークでは, dtype=torch.float32 と指定することで,32bit の浮動小数点型を用いている. ディープラーニングの学習および推論の計算には,32bit 型,場合によっては 16bit 型が使われるのが一般的である. これの主な理由として,教師データやミニバッチに起因するノイズが,浮動小数点の精度よりも大きいことがあげられる. 32bit/16bit を採用することで,メモリー消費を抑えたり,計算速度の向上が達成できる.

上記のベンチマークから,GPU を用いることで,約 10 倍のスピードアップを実現することができた. スピードアップの性能は,演算の種類や行列のサイズに依存する. 行列積は,そのなかでも最も速度向上が見込まれる演算の一つである.

実践ディープラーニング! MNIST 手書き数字認識タスク

ここまで,AWS 上でディープラーニングの計算をするための概念や前提知識をながながと説明してきたが,ついにここからディープラーニングの計算を実際に走らせてみる.

ここでは,機械学習のタスクで最も初歩的かつ有名な MNIST データセットを使った数字認識を扱う (figure_title). これは,0 から 9 までの手書きの数字の画像が与えられ,その数字が何の数字なのかを当てる,というシンプルなタスクである.

MNIST 手書き数字データセット

今回は, MNIST 文字認識タスクを,畳み込みニューラルネットワーク (Convolutional Neural Network; CNN) を使って解く. ソースコードは /handson/minist/pytorch/ にある mnist.ipynbsimple_mnist.py である. なお,このプログラムは, PyTorch の公式 Example Project 集 を参考に,多少の改変を行ったものである.

まずは,カスタムのクラスや関数が定義された simple_mnist.py をアップロードしよう (figure_title). 画面右上の "Upload" ボタンをクリックし,ファイルを選択することでアップロードができる. この Python プログラムの中に,CNN のモデルや,学習の各イテレーションにおけるパラメータの更新などが記述されている. 今回はこの中身を説明することはしないが,興味のある読者は自身でソースコードを読んでみるとよい.

 をアップロード

simple_mnist.py をアップロードできたら,次に新しい notebook を作成しよう. "conda_pytorch_p36" の環境を選択することを忘れずに.

新しいノートブックが起動したら,まずは必要なライブラリをインポートしよう.

python
import torch
import torch.optim as optim
import torchvision
from torchvision import datasets, transforms
from matplotlib import pyplot as plt

# custom functions and classes
from simple_mnist import Model, train, evaluate
import torch
import torch.optim as optim
import torchvision
from torchvision import datasets, transforms
from matplotlib import pyplot as plt

# custom functions and classes
from simple_mnist import Model, train, evaluate

torchvision パッケージには,MNIST データセットをロードするなどの便利な関数が含まれている. また,今回のハンズオンで使うカスタムのクラス・関数 (Model, train, evaluate) のインポートを行っている.

次に,MNIST テストデータをダウンロードしよう. 同時に,画像データの輝度の正規化も行っている.

python
transf = transforms.Compose([transforms.ToTensor(),
                             transforms.Normalize((0.1307,), (0.3081,))])

trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transf)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)

testset = datasets.MNIST(root='./data', train=False, download=True, transform=transf)
testloader = torch.utils.data.DataLoader(testset, batch_size=1000, shuffle=True)
transf = transforms.Compose([transforms.ToTensor(),
                             transforms.Normalize((0.1307,), (0.3081,))])

trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transf)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)

testset = datasets.MNIST(root='./data', train=False, download=True, transform=transf)
testloader = torch.utils.data.DataLoader(testset, batch_size=1000, shuffle=True)

今回扱う MNIST データは 28x28 ピクセルの正方形の画像(モノクロ)と,それぞれのラベル(0 - 9 の数字)の組で構成されている. いくつかのデータを抽出して,可視化してみよう. figure_title のような出力が得られるはずである.

python
examples = iter(testloader)
example_data, example_targets = examples.next()

print("Example data size:", example_data.shape)

fig = plt.figure(figsize=(10,4))
for i in range(10):
    plt.subplot(2,5,i+1)
    plt.tight_layout()
    plt.imshow(example_data[i][0], cmap='gray', interpolation='none')
    plt.title("Ground Truth: {}".format(example_targets[i]))
    plt.xticks([])
    plt.yticks([])
plt.show()
examples = iter(testloader)
example_data, example_targets = examples.next()

print("Example data size:", example_data.shape)

fig = plt.figure(figsize=(10,4))
for i in range(10):
    plt.subplot(2,5,i+1)
    plt.tight_layout()
    plt.imshow(example_data[i][0], cmap='gray', interpolation='none')
    plt.title("Ground Truth: {}".format(example_targets[i]))
    plt.xticks([])
    plt.yticks([])
plt.show()

MNIST の手書き数字画像とその教師ラベル

次に, CNN のモデルを定義する.

python
model = Model()
model.to("cuda") # load to GPU
model = Model()
model.to("cuda") # load to GPU

今回使う Modelsimple_mnist.py の中で定義されている. このモデルは,figure_title に示したような,2層の畳み込み層と 2 層の全結合層からなるネットワークである. 出力層 (output layer) には Softmax 関数を使用し,損失関数 (Loss function) には 負の対数尤度関数 (Negative log likelyhood; NLL) を使用している.

本ハンズオンで使用するニューラルネットの構造.

続いて, CNN のパラメータを更新する最適化アルゴリズムを定義する. ここでは, 確率的勾配降下法 (Stochastic Gradient Descent; SGD) を使用している.

python
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)

これで,準備が整った. CNN の学習ループを開始しよう!

python
train_losses = []
for epoch in range(5):
    losses = train(model, trainloader, optimizer, epoch)
    train_losses = train_losses + losses
    test_loss, test_accuracy = evaluate(model, testloader)
    print(f"\nTest set: Average loss: {test_loss:.4f}, Accuracy: {test_accuracy:.1f}%\n")

plt.figure(figsize=(7,5))
plt.plot(train_losses)
plt.xlabel("Iterations")
plt.ylabel("Train loss")
plt.show()
train_losses = []
for epoch in range(5):
    losses = train(model, trainloader, optimizer, epoch)
    train_losses = train_losses + losses
    test_loss, test_accuracy = evaluate(model, testloader)
    print(f"\nTest set: Average loss: {test_loss:.4f}, Accuracy: {test_accuracy:.1f}%\n")

plt.figure(figsize=(7,5))
plt.plot(train_losses)
plt.xlabel("Iterations")
plt.ylabel("Train loss")
plt.show()

ここでは 5 エポック分の学習を行っている. GPU を使えば,これくらいの計算であれば 1 分程度で完了するだろう.

出力として, figure_title のようなプロットが得られるはずである. イテレーションを重ねるにつれて,損失関数 (Loss function) の値が減少している (=精度が向上している) ことがわかる.

学習の進行に対する Train loss の変化

出力にはテキスト形式で各エポック終了後のテストデータに対する精度も表示されている. 最終的には 98% 以上の極めて高い精度を実現できていることが確認できるだろう (figure_title).

学習したCNNのテストデータに対するスコア (5エポック後)

学習した CNN の推論結果を可視化してみよう. 次のコードを実行することで, figure_title のような出力が得られるだろう. この図で,下段右から二番目は,"1"に近い見た目をしているが,きちんと"9"と推論できている. なかなか賢い CNN を作り出すことができたようだ!

python
model.eval()

with torch.no_grad():
    output = model(example_data.to("cuda"))

fig = plt.figure(figsize=(10,4))
for i in range(10):
    plt.subplot(2,5,i+1)
    plt.tight_layout()
    plt.imshow(example_data[i][0], cmap='gray', interpolation='none')
    plt.title("Prediction: {}".format(output.data.max(1, keepdim=True)[1][i].item()))
    plt.xticks([])
    plt.yticks([])
plt.show()
model.eval()

with torch.no_grad():
    output = model(example_data.to("cuda"))

fig = plt.figure(figsize=(10,4))
for i in range(10):
    plt.subplot(2,5,i+1)
    plt.tight_layout()
    plt.imshow(example_data[i][0], cmap='gray', interpolation='none')
    plt.title("Prediction: {}".format(output.data.max(1, keepdim=True)[1][i].item()))
    plt.xticks([])
    plt.yticks([])
plt.show()

学習した CNN による,MNIST画像の推論結果

最後に,学習したニューラルネットワークのパラメータを mnist_cnn.pt というファイル名で保存しておこう. これで,将来いつでも今回学習したモデルを再現し,別の実験に使用することができる.

python
torch.save(model.state_dict(), "mnist_cnn.pt")
torch.save(model.state_dict(), "mnist_cnn.pt")

以上が, AWS クラウドの仮想サーバーを立ち上げ,最初のディープラーニングの計算を行う一連の流れである. MNIST 文字認識のタスクを行うニューラルネットを,クラウド上の GPU を使って高速に学習させ,現実的な問題を一つ解くことができたのである. 興味のある読者は,今回のハンズオンを雛形に,自分の所望の計算を走らせてみるとよいだろう.

スタックの削除

これにて,ハンズオン第二回の内容はすべて説明した. クラウドの利用料金を最小化するため,使い終わった EC2 インスタンスはすぐさま削除しよう.

ハンズオン第一回と同様に, AWS の CloudFormation コンソールか, AWS CLI により削除を実行する (詳細は (#handson_01_delete_stack) 参照).

sh
$ cdk destroy
$ cdk destroy

スタックの削除は各自で必ず行うこと! 行わなかった場合,EC2 インスタンスの料金が発生し続けることになる! g4dn.xlarge は $0.71 / hour の料金設定なので,一日起動しつづけると約$17 の請求が発生することになる!

AWS のバジェットアラート

AWS の初心者が (あるいは経験者も) しばしば陥る失敗が,インスタンスの停止忘れなどで無駄なリソースがクラウドで放置されてしまい,巨大な額の請求が届く,というミスだ. 特に,開発を行っている間はこのような事態は起こりうるものだと思って,備えておかなければならない. このような事態を未然に防ぐため, AWS Budgets という機能が無料で提供されている. AWS Budgets を利用することで,月の利用金額がある閾値を超えた場合にユーザーにメールが送信される,などのアラートを設定することができる. 詳細な手順は AWS の公式ブログ "Getting Started with AWS Budgets" を参照のこと. 本書の読者も,ぜひこのタイミングでアラートを設定しておくことを推奨する.

]]>
<![CDATA[Hands-on #3: AWS で自動質問回答ボットを走らせる ]]> https://note.toshiki.dev/development/aws/handson-qabot https://note.toshiki.dev/development/aws/handson-qabot Thu, 01 Jul 2021 00:00:00 GMT Hands-on #3: AWS で自動質問回答ボットを走らせる

ハンズオン第三回では, Docker と ECS を駆使した機械学習アプリケーションを実装しよう. 具体的には,深層学習による自然言語処理を行うことで,クライアントから与えられた文章題に対して回答を生成する,自動 Question & Answering ボットを作成しよう. ECS を利用することで,ジョブの数によって動的にインスタンスの数を制御し,並列にタスクを実行するようなシステムを構築しよう.

通常の機械学習のワークフローでは,モデルの訓練 ⇒ 推論 (データへの適用) が基本的な流れである. しかしながら, GPU 搭載型の EC2 クラスターを使ったモデルの訓練はやや難易度が高いため,次章 ( (#sec_aws_batch)) で取り扱う. 本章は,クラウド上でのクラスターの構築・タスクの管理などの概念に慣れるため,よりシンプルな実装で実現できる Fargate クラスターを用いた推論計算の並列化を紹介する.

Fargate

ハンズオンに入っていく前に, Fargate という AWS の機能を知っておく必要がある (figure_title).

Fargate のアイコン

ECS の概要を示した (#ecs_overview) をもう一度見てみよう. この図で, ECS の管理下にあるクラスターが示されているが,このクラスターの中で計算を行う実体としては二つの選択肢がある. EC2 あるいは Fargate のいずれかである. EC2 を用いた場合は,先の章 ( (#sec_first_ec2), (#sec_jupyter_and_deep_learning)) で説明したような流れでインスタンスが起動し,計算が実行される. しかし, EC2 を用いた計算機クラスターの作成・管理は技術的な難易度がやや高いので,次章 ( (#sec_aws_batch)) で説明することにする.

Fargate とは, ECS での利用に特化して設計された,コンテナを使用した計算タスクを走らせるための仕組みである. 計算を走らせるという点では EC2 と役割は似ているが, Fargate は EC2 インスタンスのような物理的実体はもたない. 物理的実体をもたないというのは,たとえば SSH でログインすることは基本的に想定されていないし,なにかのソフトウェアをインストールしたりなどの概念も存在しない. Fargate ではすべての計算は Docker コンテナを介して行われる. すなわち, Fargate を利用するには,ユーザーは最初に所望の Docker イメージを指定しておき, Fargate は docker run のコマンドを使用することで計算タスクを実行する. Fargate を用いる利点は, Fargate を ECS のクラスターに指定すると,スケーリングなどの操作が簡単な設定・プログラムで構築できる点である.

Fargate では, EC2 と同様に CPU とメモリーのサイズを必要な分だけ指定できる. 執筆時点では, CPU は 0.25 - 4 コア, RAM は 0.5 - 30 GB の間で選択することができる (詳しくは 公式ドキュメンテーション "Amazon ECS on AWS Fargate" 参照). クラスターのスケーリングが容易な分, Fargate では EC2 ほど大きな CPU コア・ RAM 容量を単一インスタンスに付与することができず,また GPU を利用することもできない.

以上が Fargate の概要であったが,くどくど言葉で説明してもなかなかピンとこないだろう. ここからは実際に手を動かしながら, ECS と Fargate を使った並列タスクの処理の仕方を学んでいこう.

厳密には, ECS に付与するクラスターには EC2 と Fargate のハイブリッドを使用することも可能である.

準備

ハンズオンのソースコードは GitHub の handson/qa-bot にある.

本ハンズオンの実行には,第一回ハンズオンで説明した準備 ( (#handson_01_prep)) が整っていることを前提とする. また, Docker が自身のローカルマシンにインストール済みであることも必要である.

このハンズオンでは 1CPU/4GB RAM の Fargate インスタンスを使用する. 計算の実行には 0.025 $/hour のコストが発生することに注意.

Transformer を用いた question-answering プログラム

このハンズオンで開発する,自動質問回答システムをより具体的に定義しよう. 次のような文脈 (context) と質問 (question) が与えられた状況を想定する.

txt
context: Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist who developed the theory of relativity, one of the two pillars of modern physics (alongside quantum mechanics). His work is also known for its influence on the philosophy of science. He is best known to the general public for his mass–energy equivalence formula E = mc2, which has been dubbed \"the world's most famous equation\". He received the 1921 Nobel Prize in Physics \"for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect\", a pivotal step in the development of quantum theory.

question: In what year did Einstein win the Nobel prize?
context: Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist who developed the theory of relativity, one of the two pillars of modern physics (alongside quantum mechanics). His work is also known for its influence on the philosophy of science. He is best known to the general public for his mass–energy equivalence formula E = mc2, which has been dubbed \"the world's most famous equation\". He received the 1921 Nobel Prize in Physics \"for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect\", a pivotal step in the development of quantum theory.

question: In what year did Einstein win the Nobel prize?

今回作成する自動回答システムは,このような問題に対して, context に含まれる文字列から正解となる言葉を見つけ出すものとする. 上の問題では,次のような回答を返すべきである.

answer: 1921

人間にとっては,このような文章を理解することは容易であるが,コンピュータにそれを解かせるのは難しいことは容易に想像ができるだろう. しかし,近年の深層学習を使った自然言語処理の進歩は著しく,上で示したような例題などは極めて高い正答率で回答できるモデルを作ることができる.

今回は, huggingface/transformers で公開されている学習済みの言語モデルを利用することで,上で定義した問題を解く Q&A ボットを作る. この Q&A ボットは Transformer とよばれるモデルを使った自然言語処理に支えられえている (figure_title). このプログラムを, Docker にパッケージしたものが 著者の Docker Hub リポジトリ に用意してある. クラウドの設計に入る前に,まずはこのプログラムを単体で動かしてみよう.

Transformer モデルアーキテクチャ (画像出典: Vaswani+ 2017)

なお,今回は学習済みのモデルを用いているので,私達が行うのは与えられた入力をモデルに投入して予測を行う (推論) のみである. 推論の演算は, CPU だけでも十分高速に行うことができるので,コストの削減と,実装をシンプルにする目的で,このハンズオンでは GPU は利用しない. 一般的に, ニューラルネットは学習のほうが圧倒的に計算コストが大きく,そのような場合に GPU はより威力を発揮する.

次のコマンドで,今回使う Docker image を ローカルにダウンロード (pull) してこよう.

sh
$ docker pull tomomano/qabot:latest
$ docker pull tomomano/qabot:latest

pull できたら,早速この Docker に質問を投げかけてみよう. まずは context と question をコマンドラインの変数として定義する.

sh
$ context="Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist who developed the theory of relativity, one of the two pillars of modern physics (alongside quantum mechanics). His work is also known for its influence on the philosophy of science. He is best known to the general public for his mass–energy equivalence formula E = mc2, which has been dubbed the world's most famous equation. He received the 1921 Nobel Prize in Physics for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect, a pivotal step in the development of quantum theory."
$ question="In what year did Einstein win the Nobel prize ?"
$ context="Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist who developed the theory of relativity, one of the two pillars of modern physics (alongside quantum mechanics). His work is also known for its influence on the philosophy of science. He is best known to the general public for his mass–energy equivalence formula E = mc2, which has been dubbed the world's most famous equation. He received the 1921 Nobel Prize in Physics for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect, a pivotal step in the development of quantum theory."
$ question="In what year did Einstein win the Nobel prize ?"

そうしたら,次のコマンドによってコンテナを実行する.

sh
$ docker run tomomano/qabot "${context}" "${question}" foo --no_save
$ docker run tomomano/qabot "${context}" "${question}" foo --no_save

今回用意した Docker image は,第一引数に context となる文字列を,第二引数に question に相当する文字列を受けつける. 第三引数,第四引数については,クラウドに展開するときの実装上の都合なので,いまは気にしなくてよい.

このコマンドを実行すると,次のような出力が得られるはずである.

json
{ "score": 0.9881729286683587, "start": 437, "end": 441, "answer": "1921" }
{ "score": 0.9881729286683587, "start": 437, "end": 441, "answer": "1921" }

"score" は正解の自信度を表す数字で, [0,1] の範囲で与えられる. "start", "end" は, context 中の何文字目が正解に相当するかを示しており, "answer" が正解と予測された文字列である. 1921 年という,正しい答えが返ってきていることに注目してほしい.

もう少し難しい質問を投げかけてみよう.

sh
$ question="Why did Einstein win the Nobel prize ?"
$ docker run tomomano/qabot "${context}" "${question}" foo --no_save
$ question="Why did Einstein win the Nobel prize ?"
$ docker run tomomano/qabot "${context}" "${question}" foo --no_save

出力:

json
{
    "score": 0.5235594527494207,
    "start": 470,
    "end": 506,
    "answer": "his services to theoretical physics,"
}
{
    "score": 0.5235594527494207,
    "start": 470,
    "end": 506,
    "answer": "his services to theoretical physics,"
}

今度は, score が 0.52 と,少し自信がないようだが,それでも正しい答えにたどりつけていることがわかる.

このように, 深層学習に支えられた言語モデルを用いることで,実用にも役に立ちそうな Q&A ボットを実現できていることがわかる. 以降では,このプログラムをクラウドに展開することで,大量の質問に自動で対応できるようなシステムを設計していく.

今回使用する Question & Answering システムには, DistilBERT という Transformer を基にした言語モデルが用いられている. 興味のある読者は, 原著論文 を参照してもらいたい. また, huggingface/transformers による DistilBert の実装のドキュメンテーションは 公式ドキュメンテーション を参照のこと.

今回提供する Q-A ボットの Docker のソースコードは https://github.com/andatoshiki/toshiki-notebookblob/main/handson/qa-bot/docker/Dockerfile にある.

アプリケーションの説明

このハンズオンで作成するアプリケーションの概要を figure_title に示す.

アプリケーションのアーキテクチャ

簡単にまとめると,以下のような設計である.

  • クライアントは,質問を AWS 上のアプリケーションに送信する.

  • 質問のタスクは ECS によって処理される.

  • ECS は, Docker Hub から,イメージをダウンロードする.

  • 次に,ECS はクラスター内に新たな Fargate インスタンスを立ち上げ,ダウンロードされた Docker イメージをこの新規インスタンスに配置する.

    • このとき,一つの質問に対し一つの Fargate インスタンスを立ち上げることで,複数の質問を並列的に処理できるようにする.
  • ジョブが実行される.

  • ジョブの実行結果 (質問への回答) は, データベース (DynamoDB) に書き込まれる.

  • 最後に,クライアントは DynamoDB から質問への回答を読み取る.

それでは,プログラムのソースコードを見てみよう (handson/qa-bot/app.py).

python
class EcsClusterQaBot(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        # dynamoDB table to store questions and answers
        table = dynamodb.Table(
            self, "EcsClusterQaBot-Table",
            partition_key=dynamodb.Attribute(
                name="item_id", type=dynamodb.AttributeType.STRING
            ),
            billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        #
        vpc = ec2.Vpc(
            self, "EcsClusterQaBot-Vpc",
            max_azs=1,
        )

        #
        cluster = ecs.Cluster(
            self, "EcsClusterQaBot-Cluster",
            vpc=vpc,
        )

        #
        taskdef = ecs.FargateTaskDefinition(
            self, "EcsClusterQaBot-TaskDef",
            cpu=1024, # 1 CPU
            memory_limit_mib=4096, # 4GB RAM
        )

        # grant permissions
        table.grant_read_write_data(taskdef.task_role)
        taskdef.add_to_task_role_policy(
            iam.PolicyStatement(
                effect=iam.Effect.ALLOW,
                resources=["*"],
                actions=["ssm:GetParameter"]
            )
        )

        #
        container = taskdef.add_container(
            "EcsClusterQaBot-Container",
            image=ecs.ContainerImage.from_registry(
                "tomomano/qabot:latest"
            ),
        )
class EcsClusterQaBot(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        # dynamoDB table to store questions and answers
        table = dynamodb.Table(
            self, "EcsClusterQaBot-Table",
            partition_key=dynamodb.Attribute(
                name="item_id", type=dynamodb.AttributeType.STRING
            ),
            billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        #
        vpc = ec2.Vpc(
            self, "EcsClusterQaBot-Vpc",
            max_azs=1,
        )

        #
        cluster = ecs.Cluster(
            self, "EcsClusterQaBot-Cluster",
            vpc=vpc,
        )

        #
        taskdef = ecs.FargateTaskDefinition(
            self, "EcsClusterQaBot-TaskDef",
            cpu=1024, # 1 CPU
            memory_limit_mib=4096, # 4GB RAM
        )

        # grant permissions
        table.grant_read_write_data(taskdef.task_role)
        taskdef.add_to_task_role_policy(
            iam.PolicyStatement(
                effect=iam.Effect.ALLOW,
                resources=["*"],
                actions=["ssm:GetParameter"]
            )
        )

        #
        container = taskdef.add_container(
            "EcsClusterQaBot-Container",
            image=ecs.ContainerImage.from_registry(
                "tomomano/qabot:latest"
            ),
        )
  • ここでは,回答の結果を書き込むためのデータベースを用意している. DynamoDB については,サーバーレスアーキテクチャの章で扱うので,今は気にしなくてよい.

  • ここでは,ハンズオン #1, #2 で行ったのと同様に, VPC を定義している.

  • ここで, ECS のクラスター (cluster) を定義している. クラスターとは,仮想サーバーのプールのことであり,クラスターの中に複数の仮想インスタンスを配置する.

  • ここで,実行するタスクを定義している (task definition).

  • ここで, タスクの実行で使用する Docker イメージを定義している.

ECS と Fargate

ECS と Fargate の部分について,コードをくわしく見てみよう.

python
cluster = ecs.Cluster(
    self, "EcsClusterQaBot-Cluster",
    vpc=vpc,
)

taskdef = ecs.FargateTaskDefinition(
    self, "EcsClusterQaBot-TaskDef",
    cpu=1024, # 1 CPU
    memory_limit_mib=4096, # 4GB RAM
)

container = taskdef.add_container(
    "EcsClusterQaBot-Container",
    image=ecs.ContainerImage.from_registry(
        "tomomano/qabot:latest"
    ),
)
cluster = ecs.Cluster(
    self, "EcsClusterQaBot-Cluster",
    vpc=vpc,
)

taskdef = ecs.FargateTaskDefinition(
    self, "EcsClusterQaBot-TaskDef",
    cpu=1024, # 1 CPU
    memory_limit_mib=4096, # 4GB RAM
)

container = taskdef.add_container(
    "EcsClusterQaBot-Container",
    image=ecs.ContainerImage.from_registry(
        "tomomano/qabot:latest"
    ),
)

cluster = の箇所で,空の ECS クラスターを定義している.

次に, taskdef=ecs.FargateTaskDefinition の箇所で, Fargate インスタンスを使ったタスクを定義しており,とくにここでは 1 CPU, 4GB RAM というマシンスペックを指定している. また,このようにして定義されたタスクは,デフォルトで 1 タスクにつき 1 インスタンスが使用される.

最後に, container = の箇所で,タスクの実行で使用する Docker image を定義している. ここでは, Docker Hub に置いてある image をダウンロードしてくるよう指定している.

このようにわずか数行のコードであるが,これだけで前述したような,タスクのスケジューリングなどが自動で実行される.

このコードで cpu=1024 と指定されているのに注目してほしい. これは CPU ユニットと呼ばれる数で, 以下の換算表に従って仮想 CPU (virtual CPU; vCPU) が割り当てられる. 1024 が 1 CPU に相当する. 0.25 や 0.5 vCPU などの数字は,それぞれ実効的に 1/4, 1/2 の CPU 時間が割り当てられることを意味する. また, CPU ユニットによって使用できるメモリー量も変わってくる. たとえば, 1024 CPU ユニットを選択した場合は, 2 から 8 GB の範囲でのみメモリー量を指定することができる. 最新の情報は 公式ドキュメンテーション "Amazon ECS on AWS Fargate" を参照のこと.

CPU ユニットと 指定可能なメモリー量の換算表

CPU ユニット

メモリーの値

256 (.25 vCPU)

0.5 GB, 1 GB, 2 GB

512 (.5 vCPU)

1 GB, 2 GB, 3 GB, 4 GB

1024 (1 vCPU)

2 GB, 3 GB, 4 GB, 5 GB, 6 GB, 7 GB, 8 GB

2048 (2 vCPU)

Between 4 GB and 16 GB in 1-GB increments

4096 (4 vCPU)

Between 8 GB and 30 GB in 1-GB increments

スタックのデプロイ

スタックの中身が理解できたところで,早速スタックをデプロイしてみよう.

デプロイの手順は,これまでのハンズオンとほとんど共通である. SSH によるログインの必要がないので,むしろ単純なくらいである. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). それぞれの意味を忘れてしまった場合は,ハンズオン 1, 2 に戻って復習していただきたい. シークレットキーの設定も忘れずに ( (#aws_cli_install)).

sh
# プロジェクトのディレクトリに移動
$ cd handson/qa-bot

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd handson/qa-bot

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイのコマンドが無事に実行されれば, figure_title のような出力が得られるはずである.

CDKデプロイ実行後の出力

AWS コンソールにログインして,デプロイされたスタックの中身を確認してみよう. コンソールから,ECS のページに行くと figure_title のような画面が表示されるはずである. EcsClusterQaBot-XXXX という名前ついたクラスターを見つけよう.

Cluster というのが,先ほど説明したとおり,複数の仮想インスタンスを束ねる一つの単位である. figure_title で, FARGATE という文字の下に 0 Running tasks, 0 Pending tasks と表示されていることを確認しよう. この時点では一つもタスクが走っていないので,数字はすべて 0 になっている.

ECS コンソール画面

続いて,この画面の左のメニューバーから Task Definitions という項目を見つけ,クリックしよう. 移動した先のページで EcsClusterQaBotEcsClusterQaBotTaskDefXXXX という項目が見つかるので,開く. 開いた先のページをスクロールすると figure_title に示したような情報が見つかるだろう. 使用する CPU ・メモリーの量や, Docker container の実行に関する設定などが,この Task Definition の画面から確認することができる.

Task definition の確認

タスクの実行

それでは,質問をデプロイしたクラウドに提出してみよう.

ECS にタスクを投入するのはやや複雑なので,タスクの投入を簡単にするプログラム (run_task.py) を用意した (handson/qa-bot/run_task.py).

次のようなコマンドで,ECS クラスターに新しい質問を投入することができる.

sh
$ python run_task.py ask "A giant peach was flowing in the river. She picked it up and brought it home. Later, a healthy baby was born from the peach. She named the baby Momotaro." "What is the name of the baby?"
$ python run_task.py ask "A giant peach was flowing in the river. She picked it up and brought it home. Later, a healthy baby was born from the peach. She named the baby Momotaro." "What is the name of the baby?"

run_task.py を実行するには, コマンドラインで AWS の認証情報が設定されていることが前提である.

"ask" の引数に続き,文脈 (context) と質問 (question) を引数として渡している.

このコマンドを実行すると, "Waiting for the task to finish…" と出力が表示され,回答を得るまでしばらく待たされる. この間, AWS では ECS がタスクを受理し,新しい Fargate のインスタンスを起動し, Docker イメージをそのインスタンスに配置する,という一連の処理がなされている. AWS コンソールから,この一連の様子をモニタリングしてみよう.

先ほどの ECS コンソール画面にもどり,クラスターの名前をクリックすることで,クラスターの詳細画面を開く. 次に, "Tasks" という名前のタブがあるので,それを開く (figure_title). すると,実行中のタスクの一覧が表示されるだろう.

ECS のタスクの実行状況をモニタリング

figure_title で見て取れるように, "Last status = Pending" となっていることから,この時点では,タスクを実行する準備をしている段階である,ということがわかる. Fargate のインスタンスを起動し, Docker image を配置するまでおよそ 1-2 分の時間がかかる.

しばらく待つうちに, Status が "RUNNING" に遷移し,計算が始まる. 計算が終わると, Status は "STOPPED" に遷移し, ECS によって Fargate インスタンスは自動的にシャットダウンされる.

figure_title の画面から, "Task" の列にあるタスク ID クリックすることで,タスクの詳細画面を開いてみよう (figure_title). "Last status", "Platform version" など,タスクの情報が表示されている. また, "Logs" のタブを開くことで,コンテナの吐き出した実行ログを閲覧することができる.

質問タスクの実行結果

さて, run_task.py を実行したコマンドラインに戻ってきてみると, figure_title のような出力が得られているはずである. "Momotaro" という正しい回答が返ってきている!

質問タスクの実行結果

タスクの同時実行

さて,先ほどはたった一つの質問を投入したわけだが,今回設計したアプリケーションは, ECS と Fargate を使うことで同時にたくさんの質問を処理することができる. 実際に,たくさんの質問を一度に投入してみよう. run_task.pyask_many というオプションを付けることで,複数の質問を一度に送信できる. 質問の内容は handson/qa-bot/problems.json に定義されている.

次のようなコマンドを実行しよう.

sh
$ python run_task.py ask_many
$ python run_task.py ask_many

このコマンドを実行した後で,先ほどの ECS コンソールに行き,タスクの一覧を見てみよう (figure_title). 複数の Fargate インスタンスが起動され,タスクが並列に実行されているのがわかる.

複数の質問タスクを同時に投入する

すべてのタスクのステータスが "STOPPED" になったことを確認した上で,質問への回答を取得しよう. それには,次のコマンドを実行する.

sh
$ python run_task.py list_answers
$ python run_task.py list_answers

結果として, figure_title のような出力が得られるだろう. 複雑な文章問題に対し,高い正答率で回答できていることがわかるだろう.

 の実行結果

おめでとう! ここまでついてこれた読者はとても初歩的ながらも,深層学習による言語モデルを使って自動で質問への回答を生成するシステムを創り上げることができた! それも,数百の質問にも同時に対応できるような,とても高いスケーラビリティーをもったシステムである! 今回は GUI (Graphical User Interface) を用意することはしなかったが,このシステムに簡単な GUI を追加すればなかなか立派なウェブサービスとして運用できるだろう.

run_task.py で質問を投入し続けると,回答を記録しているデータベースにどんどんエントリーが溜まっていく. これらのエントリーをすべて消去するには,次のコマンドを使う.

sh
$ python run_task.py clear
$ python run_task.py clear

スタックの削除

これにて,今回のハンズオンは終了である. 最後にスタックを削除しよう.

スタックを削除するには,前回までと同様に, AWS コンソールにログインし CloudFormation の画面から DELETE ボタンをクリックするか,コマンドラインからコマンドを実行する. コマンドラインから行う場合は,次のコマンドを使用する.

sh
$ cdk destroy
$ cdk destroy
]]>
Hands-on #3: AWS で自動質問回答ボットを走らせる

ハンズオン第三回では, Docker と ECS を駆使した機械学習アプリケーションを実装しよう. 具体的には,深層学習による自然言語処理を行うことで,クライアントから与えられた文章題に対して回答を生成する,自動 Question & Answering ボットを作成しよう. ECS を利用することで,ジョブの数によって動的にインスタンスの数を制御し,並列にタスクを実行するようなシステムを構築しよう.

通常の機械学習のワークフローでは,モデルの訓練 ⇒ 推論 (データへの適用) が基本的な流れである. しかしながら, GPU 搭載型の EC2 クラスターを使ったモデルの訓練はやや難易度が高いため,次章 ( (#sec_aws_batch)) で取り扱う. 本章は,クラウド上でのクラスターの構築・タスクの管理などの概念に慣れるため,よりシンプルな実装で実現できる Fargate クラスターを用いた推論計算の並列化を紹介する.

Fargate

ハンズオンに入っていく前に, Fargate という AWS の機能を知っておく必要がある (figure_title).

Fargate のアイコン

ECS の概要を示した (#ecs_overview) をもう一度見てみよう. この図で, ECS の管理下にあるクラスターが示されているが,このクラスターの中で計算を行う実体としては二つの選択肢がある. EC2 あるいは Fargate のいずれかである. EC2 を用いた場合は,先の章 ( (#sec_first_ec2), (#sec_jupyter_and_deep_learning)) で説明したような流れでインスタンスが起動し,計算が実行される. しかし, EC2 を用いた計算機クラスターの作成・管理は技術的な難易度がやや高いので,次章 ( (#sec_aws_batch)) で説明することにする.

Fargate とは, ECS での利用に特化して設計された,コンテナを使用した計算タスクを走らせるための仕組みである. 計算を走らせるという点では EC2 と役割は似ているが, Fargate は EC2 インスタンスのような物理的実体はもたない. 物理的実体をもたないというのは,たとえば SSH でログインすることは基本的に想定されていないし,なにかのソフトウェアをインストールしたりなどの概念も存在しない. Fargate ではすべての計算は Docker コンテナを介して行われる. すなわち, Fargate を利用するには,ユーザーは最初に所望の Docker イメージを指定しておき, Fargate は docker run のコマンドを使用することで計算タスクを実行する. Fargate を用いる利点は, Fargate を ECS のクラスターに指定すると,スケーリングなどの操作が簡単な設定・プログラムで構築できる点である.

Fargate では, EC2 と同様に CPU とメモリーのサイズを必要な分だけ指定できる. 執筆時点では, CPU は 0.25 - 4 コア, RAM は 0.5 - 30 GB の間で選択することができる (詳しくは 公式ドキュメンテーション "Amazon ECS on AWS Fargate" 参照). クラスターのスケーリングが容易な分, Fargate では EC2 ほど大きな CPU コア・ RAM 容量を単一インスタンスに付与することができず,また GPU を利用することもできない.

以上が Fargate の概要であったが,くどくど言葉で説明してもなかなかピンとこないだろう. ここからは実際に手を動かしながら, ECS と Fargate を使った並列タスクの処理の仕方を学んでいこう.

厳密には, ECS に付与するクラスターには EC2 と Fargate のハイブリッドを使用することも可能である.

準備

ハンズオンのソースコードは GitHub の handson/qa-bot にある.

本ハンズオンの実行には,第一回ハンズオンで説明した準備 ( (#handson_01_prep)) が整っていることを前提とする. また, Docker が自身のローカルマシンにインストール済みであることも必要である.

このハンズオンでは 1CPU/4GB RAM の Fargate インスタンスを使用する. 計算の実行には 0.025 $/hour のコストが発生することに注意.

Transformer を用いた question-answering プログラム

このハンズオンで開発する,自動質問回答システムをより具体的に定義しよう. 次のような文脈 (context) と質問 (question) が与えられた状況を想定する.

txt
context: Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist who developed the theory of relativity, one of the two pillars of modern physics (alongside quantum mechanics). His work is also known for its influence on the philosophy of science. He is best known to the general public for his mass–energy equivalence formula E = mc2, which has been dubbed \"the world's most famous equation\". He received the 1921 Nobel Prize in Physics \"for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect\", a pivotal step in the development of quantum theory.

question: In what year did Einstein win the Nobel prize?
context: Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist who developed the theory of relativity, one of the two pillars of modern physics (alongside quantum mechanics). His work is also known for its influence on the philosophy of science. He is best known to the general public for his mass–energy equivalence formula E = mc2, which has been dubbed \"the world's most famous equation\". He received the 1921 Nobel Prize in Physics \"for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect\", a pivotal step in the development of quantum theory.

question: In what year did Einstein win the Nobel prize?

今回作成する自動回答システムは,このような問題に対して, context に含まれる文字列から正解となる言葉を見つけ出すものとする. 上の問題では,次のような回答を返すべきである.

answer: 1921

人間にとっては,このような文章を理解することは容易であるが,コンピュータにそれを解かせるのは難しいことは容易に想像ができるだろう. しかし,近年の深層学習を使った自然言語処理の進歩は著しく,上で示したような例題などは極めて高い正答率で回答できるモデルを作ることができる.

今回は, huggingface/transformers で公開されている学習済みの言語モデルを利用することで,上で定義した問題を解く Q&A ボットを作る. この Q&A ボットは Transformer とよばれるモデルを使った自然言語処理に支えられえている (figure_title). このプログラムを, Docker にパッケージしたものが 著者の Docker Hub リポジトリ に用意してある. クラウドの設計に入る前に,まずはこのプログラムを単体で動かしてみよう.

Transformer モデルアーキテクチャ (画像出典: Vaswani+ 2017)

なお,今回は学習済みのモデルを用いているので,私達が行うのは与えられた入力をモデルに投入して予測を行う (推論) のみである. 推論の演算は, CPU だけでも十分高速に行うことができるので,コストの削減と,実装をシンプルにする目的で,このハンズオンでは GPU は利用しない. 一般的に, ニューラルネットは学習のほうが圧倒的に計算コストが大きく,そのような場合に GPU はより威力を発揮する.

次のコマンドで,今回使う Docker image を ローカルにダウンロード (pull) してこよう.

sh
$ docker pull tomomano/qabot:latest
$ docker pull tomomano/qabot:latest

pull できたら,早速この Docker に質問を投げかけてみよう. まずは context と question をコマンドラインの変数として定義する.

sh
$ context="Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist who developed the theory of relativity, one of the two pillars of modern physics (alongside quantum mechanics). His work is also known for its influence on the philosophy of science. He is best known to the general public for his mass–energy equivalence formula E = mc2, which has been dubbed the world's most famous equation. He received the 1921 Nobel Prize in Physics for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect, a pivotal step in the development of quantum theory."
$ question="In what year did Einstein win the Nobel prize ?"
$ context="Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist who developed the theory of relativity, one of the two pillars of modern physics (alongside quantum mechanics). His work is also known for its influence on the philosophy of science. He is best known to the general public for his mass–energy equivalence formula E = mc2, which has been dubbed the world's most famous equation. He received the 1921 Nobel Prize in Physics for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect, a pivotal step in the development of quantum theory."
$ question="In what year did Einstein win the Nobel prize ?"

そうしたら,次のコマンドによってコンテナを実行する.

sh
$ docker run tomomano/qabot "${context}" "${question}" foo --no_save
$ docker run tomomano/qabot "${context}" "${question}" foo --no_save

今回用意した Docker image は,第一引数に context となる文字列を,第二引数に question に相当する文字列を受けつける. 第三引数,第四引数については,クラウドに展開するときの実装上の都合なので,いまは気にしなくてよい.

このコマンドを実行すると,次のような出力が得られるはずである.

json
{ "score": 0.9881729286683587, "start": 437, "end": 441, "answer": "1921" }
{ "score": 0.9881729286683587, "start": 437, "end": 441, "answer": "1921" }

"score" は正解の自信度を表す数字で, [0,1] の範囲で与えられる. "start", "end" は, context 中の何文字目が正解に相当するかを示しており, "answer" が正解と予測された文字列である. 1921 年という,正しい答えが返ってきていることに注目してほしい.

もう少し難しい質問を投げかけてみよう.

sh
$ question="Why did Einstein win the Nobel prize ?"
$ docker run tomomano/qabot "${context}" "${question}" foo --no_save
$ question="Why did Einstein win the Nobel prize ?"
$ docker run tomomano/qabot "${context}" "${question}" foo --no_save

出力:

json
{
    "score": 0.5235594527494207,
    "start": 470,
    "end": 506,
    "answer": "his services to theoretical physics,"
}
{
    "score": 0.5235594527494207,
    "start": 470,
    "end": 506,
    "answer": "his services to theoretical physics,"
}

今度は, score が 0.52 と,少し自信がないようだが,それでも正しい答えにたどりつけていることがわかる.

このように, 深層学習に支えられた言語モデルを用いることで,実用にも役に立ちそうな Q&A ボットを実現できていることがわかる. 以降では,このプログラムをクラウドに展開することで,大量の質問に自動で対応できるようなシステムを設計していく.

今回使用する Question & Answering システムには, DistilBERT という Transformer を基にした言語モデルが用いられている. 興味のある読者は, 原著論文 を参照してもらいたい. また, huggingface/transformers による DistilBert の実装のドキュメンテーションは 公式ドキュメンテーション を参照のこと.

今回提供する Q-A ボットの Docker のソースコードは https://github.com/andatoshiki/toshiki-notebookblob/main/handson/qa-bot/docker/Dockerfile にある.

アプリケーションの説明

このハンズオンで作成するアプリケーションの概要を figure_title に示す.

アプリケーションのアーキテクチャ

簡単にまとめると,以下のような設計である.

  • クライアントは,質問を AWS 上のアプリケーションに送信する.

  • 質問のタスクは ECS によって処理される.

  • ECS は, Docker Hub から,イメージをダウンロードする.

  • 次に,ECS はクラスター内に新たな Fargate インスタンスを立ち上げ,ダウンロードされた Docker イメージをこの新規インスタンスに配置する.

    • このとき,一つの質問に対し一つの Fargate インスタンスを立ち上げることで,複数の質問を並列的に処理できるようにする.
  • ジョブが実行される.

  • ジョブの実行結果 (質問への回答) は, データベース (DynamoDB) に書き込まれる.

  • 最後に,クライアントは DynamoDB から質問への回答を読み取る.

それでは,プログラムのソースコードを見てみよう (handson/qa-bot/app.py).

python
class EcsClusterQaBot(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        # dynamoDB table to store questions and answers
        table = dynamodb.Table(
            self, "EcsClusterQaBot-Table",
            partition_key=dynamodb.Attribute(
                name="item_id", type=dynamodb.AttributeType.STRING
            ),
            billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        #
        vpc = ec2.Vpc(
            self, "EcsClusterQaBot-Vpc",
            max_azs=1,
        )

        #
        cluster = ecs.Cluster(
            self, "EcsClusterQaBot-Cluster",
            vpc=vpc,
        )

        #
        taskdef = ecs.FargateTaskDefinition(
            self, "EcsClusterQaBot-TaskDef",
            cpu=1024, # 1 CPU
            memory_limit_mib=4096, # 4GB RAM
        )

        # grant permissions
        table.grant_read_write_data(taskdef.task_role)
        taskdef.add_to_task_role_policy(
            iam.PolicyStatement(
                effect=iam.Effect.ALLOW,
                resources=["*"],
                actions=["ssm:GetParameter"]
            )
        )

        #
        container = taskdef.add_container(
            "EcsClusterQaBot-Container",
            image=ecs.ContainerImage.from_registry(
                "tomomano/qabot:latest"
            ),
        )
class EcsClusterQaBot(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        # dynamoDB table to store questions and answers
        table = dynamodb.Table(
            self, "EcsClusterQaBot-Table",
            partition_key=dynamodb.Attribute(
                name="item_id", type=dynamodb.AttributeType.STRING
            ),
            billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        #
        vpc = ec2.Vpc(
            self, "EcsClusterQaBot-Vpc",
            max_azs=1,
        )

        #
        cluster = ecs.Cluster(
            self, "EcsClusterQaBot-Cluster",
            vpc=vpc,
        )

        #
        taskdef = ecs.FargateTaskDefinition(
            self, "EcsClusterQaBot-TaskDef",
            cpu=1024, # 1 CPU
            memory_limit_mib=4096, # 4GB RAM
        )

        # grant permissions
        table.grant_read_write_data(taskdef.task_role)
        taskdef.add_to_task_role_policy(
            iam.PolicyStatement(
                effect=iam.Effect.ALLOW,
                resources=["*"],
                actions=["ssm:GetParameter"]
            )
        )

        #
        container = taskdef.add_container(
            "EcsClusterQaBot-Container",
            image=ecs.ContainerImage.from_registry(
                "tomomano/qabot:latest"
            ),
        )
  • ここでは,回答の結果を書き込むためのデータベースを用意している. DynamoDB については,サーバーレスアーキテクチャの章で扱うので,今は気にしなくてよい.

  • ここでは,ハンズオン #1, #2 で行ったのと同様に, VPC を定義している.

  • ここで, ECS のクラスター (cluster) を定義している. クラスターとは,仮想サーバーのプールのことであり,クラスターの中に複数の仮想インスタンスを配置する.

  • ここで,実行するタスクを定義している (task definition).

  • ここで, タスクの実行で使用する Docker イメージを定義している.

ECS と Fargate

ECS と Fargate の部分について,コードをくわしく見てみよう.

python
cluster = ecs.Cluster(
    self, "EcsClusterQaBot-Cluster",
    vpc=vpc,
)

taskdef = ecs.FargateTaskDefinition(
    self, "EcsClusterQaBot-TaskDef",
    cpu=1024, # 1 CPU
    memory_limit_mib=4096, # 4GB RAM
)

container = taskdef.add_container(
    "EcsClusterQaBot-Container",
    image=ecs.ContainerImage.from_registry(
        "tomomano/qabot:latest"
    ),
)
cluster = ecs.Cluster(
    self, "EcsClusterQaBot-Cluster",
    vpc=vpc,
)

taskdef = ecs.FargateTaskDefinition(
    self, "EcsClusterQaBot-TaskDef",
    cpu=1024, # 1 CPU
    memory_limit_mib=4096, # 4GB RAM
)

container = taskdef.add_container(
    "EcsClusterQaBot-Container",
    image=ecs.ContainerImage.from_registry(
        "tomomano/qabot:latest"
    ),
)

cluster = の箇所で,空の ECS クラスターを定義している.

次に, taskdef=ecs.FargateTaskDefinition の箇所で, Fargate インスタンスを使ったタスクを定義しており,とくにここでは 1 CPU, 4GB RAM というマシンスペックを指定している. また,このようにして定義されたタスクは,デフォルトで 1 タスクにつき 1 インスタンスが使用される.

最後に, container = の箇所で,タスクの実行で使用する Docker image を定義している. ここでは, Docker Hub に置いてある image をダウンロードしてくるよう指定している.

このようにわずか数行のコードであるが,これだけで前述したような,タスクのスケジューリングなどが自動で実行される.

このコードで cpu=1024 と指定されているのに注目してほしい. これは CPU ユニットと呼ばれる数で, 以下の換算表に従って仮想 CPU (virtual CPU; vCPU) が割り当てられる. 1024 が 1 CPU に相当する. 0.25 や 0.5 vCPU などの数字は,それぞれ実効的に 1/4, 1/2 の CPU 時間が割り当てられることを意味する. また, CPU ユニットによって使用できるメモリー量も変わってくる. たとえば, 1024 CPU ユニットを選択した場合は, 2 から 8 GB の範囲でのみメモリー量を指定することができる. 最新の情報は 公式ドキュメンテーション "Amazon ECS on AWS Fargate" を参照のこと.

CPU ユニットと 指定可能なメモリー量の換算表

CPU ユニット

メモリーの値

256 (.25 vCPU)

0.5 GB, 1 GB, 2 GB

512 (.5 vCPU)

1 GB, 2 GB, 3 GB, 4 GB

1024 (1 vCPU)

2 GB, 3 GB, 4 GB, 5 GB, 6 GB, 7 GB, 8 GB

2048 (2 vCPU)

Between 4 GB and 16 GB in 1-GB increments

4096 (4 vCPU)

Between 8 GB and 30 GB in 1-GB increments

スタックのデプロイ

スタックの中身が理解できたところで,早速スタックをデプロイしてみよう.

デプロイの手順は,これまでのハンズオンとほとんど共通である. SSH によるログインの必要がないので,むしろ単純なくらいである. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). それぞれの意味を忘れてしまった場合は,ハンズオン 1, 2 に戻って復習していただきたい. シークレットキーの設定も忘れずに ( (#aws_cli_install)).

sh
# プロジェクトのディレクトリに移動
$ cd handson/qa-bot

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd handson/qa-bot

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイのコマンドが無事に実行されれば, figure_title のような出力が得られるはずである.

CDKデプロイ実行後の出力

AWS コンソールにログインして,デプロイされたスタックの中身を確認してみよう. コンソールから,ECS のページに行くと figure_title のような画面が表示されるはずである. EcsClusterQaBot-XXXX という名前ついたクラスターを見つけよう.

Cluster というのが,先ほど説明したとおり,複数の仮想インスタンスを束ねる一つの単位である. figure_title で, FARGATE という文字の下に 0 Running tasks, 0 Pending tasks と表示されていることを確認しよう. この時点では一つもタスクが走っていないので,数字はすべて 0 になっている.

ECS コンソール画面

続いて,この画面の左のメニューバーから Task Definitions という項目を見つけ,クリックしよう. 移動した先のページで EcsClusterQaBotEcsClusterQaBotTaskDefXXXX という項目が見つかるので,開く. 開いた先のページをスクロールすると figure_title に示したような情報が見つかるだろう. 使用する CPU ・メモリーの量や, Docker container の実行に関する設定などが,この Task Definition の画面から確認することができる.

Task definition の確認

タスクの実行

それでは,質問をデプロイしたクラウドに提出してみよう.

ECS にタスクを投入するのはやや複雑なので,タスクの投入を簡単にするプログラム (run_task.py) を用意した (handson/qa-bot/run_task.py).

次のようなコマンドで,ECS クラスターに新しい質問を投入することができる.

sh
$ python run_task.py ask "A giant peach was flowing in the river. She picked it up and brought it home. Later, a healthy baby was born from the peach. She named the baby Momotaro." "What is the name of the baby?"
$ python run_task.py ask "A giant peach was flowing in the river. She picked it up and brought it home. Later, a healthy baby was born from the peach. She named the baby Momotaro." "What is the name of the baby?"

run_task.py を実行するには, コマンドラインで AWS の認証情報が設定されていることが前提である.

"ask" の引数に続き,文脈 (context) と質問 (question) を引数として渡している.

このコマンドを実行すると, "Waiting for the task to finish…" と出力が表示され,回答を得るまでしばらく待たされる. この間, AWS では ECS がタスクを受理し,新しい Fargate のインスタンスを起動し, Docker イメージをそのインスタンスに配置する,という一連の処理がなされている. AWS コンソールから,この一連の様子をモニタリングしてみよう.

先ほどの ECS コンソール画面にもどり,クラスターの名前をクリックすることで,クラスターの詳細画面を開く. 次に, "Tasks" という名前のタブがあるので,それを開く (figure_title). すると,実行中のタスクの一覧が表示されるだろう.

ECS のタスクの実行状況をモニタリング

figure_title で見て取れるように, "Last status = Pending" となっていることから,この時点では,タスクを実行する準備をしている段階である,ということがわかる. Fargate のインスタンスを起動し, Docker image を配置するまでおよそ 1-2 分の時間がかかる.

しばらく待つうちに, Status が "RUNNING" に遷移し,計算が始まる. 計算が終わると, Status は "STOPPED" に遷移し, ECS によって Fargate インスタンスは自動的にシャットダウンされる.

figure_title の画面から, "Task" の列にあるタスク ID クリックすることで,タスクの詳細画面を開いてみよう (figure_title). "Last status", "Platform version" など,タスクの情報が表示されている. また, "Logs" のタブを開くことで,コンテナの吐き出した実行ログを閲覧することができる.

質問タスクの実行結果

さて, run_task.py を実行したコマンドラインに戻ってきてみると, figure_title のような出力が得られているはずである. "Momotaro" という正しい回答が返ってきている!

質問タスクの実行結果

タスクの同時実行

さて,先ほどはたった一つの質問を投入したわけだが,今回設計したアプリケーションは, ECS と Fargate を使うことで同時にたくさんの質問を処理することができる. 実際に,たくさんの質問を一度に投入してみよう. run_task.pyask_many というオプションを付けることで,複数の質問を一度に送信できる. 質問の内容は handson/qa-bot/problems.json に定義されている.

次のようなコマンドを実行しよう.

sh
$ python run_task.py ask_many
$ python run_task.py ask_many

このコマンドを実行した後で,先ほどの ECS コンソールに行き,タスクの一覧を見てみよう (figure_title). 複数の Fargate インスタンスが起動され,タスクが並列に実行されているのがわかる.

複数の質問タスクを同時に投入する

すべてのタスクのステータスが "STOPPED" になったことを確認した上で,質問への回答を取得しよう. それには,次のコマンドを実行する.

sh
$ python run_task.py list_answers
$ python run_task.py list_answers

結果として, figure_title のような出力が得られるだろう. 複雑な文章問題に対し,高い正答率で回答できていることがわかるだろう.

 の実行結果

おめでとう! ここまでついてこれた読者はとても初歩的ながらも,深層学習による言語モデルを使って自動で質問への回答を生成するシステムを創り上げることができた! それも,数百の質問にも同時に対応できるような,とても高いスケーラビリティーをもったシステムである! 今回は GUI (Graphical User Interface) を用意することはしなかったが,このシステムに簡単な GUI を追加すればなかなか立派なウェブサービスとして運用できるだろう.

run_task.py で質問を投入し続けると,回答を記録しているデータベースにどんどんエントリーが溜まっていく. これらのエントリーをすべて消去するには,次のコマンドを使う.

sh
$ python run_task.py clear
$ python run_task.py clear

スタックの削除

これにて,今回のハンズオンは終了である. 最後にスタックを削除しよう.

スタックを削除するには,前回までと同様に, AWS コンソールにログインし CloudFormation の画面から DELETE ボタンをクリックするか,コマンドラインからコマンドを実行する. コマンドラインから行う場合は,次のコマンドを使用する.

sh
$ cdk destroy
$ cdk destroy
]]>
<![CDATA[Hands-on #5: サーバーレス入門 ]]> https://note.toshiki.dev/development/aws/handson-serverless https://note.toshiki.dev/development/aws/handson-serverless Thu, 01 Jul 2021 00:00:00 GMT Hands-on #5: サーバーレス入門

前章ではサーバーレスアーキテクチャの概要の説明を行った. 本章では,ハンズオン形式でサーバーレスクラウドを実際に動かしながら,具体的な使用方法を学んでいこう. 今回のハンズオンでは Lambda, S3, DynamoDB の三つのサーバーレスクラウドの構成要素に触れていく. それぞれについて,短いチュートリアルを用意してある.

Lambda ハンズオン

まずは, Lambda を実際に動かしてみよう. ハンズオンのソースコードは GitHub の handson/serverless/lambda に置いてある.

このハンズオンで使用するアプリケーションのスケッチを figure_title に示す. STEP 1 では,AWS CDK を使用して Python で書かれたコードを Lambda に登録する. 続いて STEP 2 では, Invoke API を使用して,同時にいくつもの Lambda を起動し,並列な計算を行う. Lambda のワークフローを体験する目的で最小限の設定である.

Lambda チュートリアルの概要

このハンズオンは,基本的に AWS Lambda の無料枠 の範囲内で実行することができる.

app.py にデプロイするプログラムが書かれている. 中身を見てみよう.

python
#
FUNC = """
import time
from random import choice, randint
def handler(event, context):
    time.sleep(randint(2,5))
    sushi = ["salmon", "tuna", "squid"]
    message = "Welcome to Cloud Sushi. Your order is " + choice(sushi)
    print(message)
    return message
"""

class SimpleLambda(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        handler = _lambda.Function(
            self, 'LambdaHandler',
            runtime=_lambda.Runtime.PYTHON_3_7,
            code=_lambda.Code.from_inline(FUNC),
            handler="index.handler",
            memory_size=128,
            timeout=core.Duration.seconds(10),
            dead_letter_queue_enabled=True,
        )
#
FUNC = """
import time
from random import choice, randint
def handler(event, context):
    time.sleep(randint(2,5))
    sushi = ["salmon", "tuna", "squid"]
    message = "Welcome to Cloud Sushi. Your order is " + choice(sushi)
    print(message)
    return message
"""

class SimpleLambda(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        handler = _lambda.Function(
            self, 'LambdaHandler',
            runtime=_lambda.Runtime.PYTHON_3_7,
            code=_lambda.Code.from_inline(FUNC),
            handler="index.handler",
            memory_size=128,
            timeout=core.Duration.seconds(10),
            dead_letter_queue_enabled=True,
        )
  • ここで, Lambda で実行されるべき関数を定義している. これは非常に単純な関数で,2-5 秒のランダムな時間スリープした後,["salmon", "tuna", "squid"] のいずれかの文字列をランダムに選択し, "Welcome to Cloud Sushi. Your order is XXXX" (XXXX は選ばれた寿司のネタ) というメッセージをリターンする.

  • 次に, Lambda に <1> で書いた関数を配置している. パラメータの意味は,文字どおりの意味なので難しくはないが,以下に解説する.

    • runtime=_lambda.Runtime.PYTHON_3_7: ここでは, Python3.7 を使って上記で定義された関数を実行せよ,と指定している. Python3.7 のほかに, Node.js, Java, Ruby, Go などの言語を指定することが可能である.

    • code=_lambda.Code.from_inline(FUNC): 実行されるべき関数が書かれたコードを指定する. ここでは, FUNC=... で定義した文字列を渡しているが,文字列以外にもファイルのパスを渡すことも可能である.

    • handler="index.handler": これは,コードの中にいくつかのサブ関数が含まれているときに,メインとサブを区別するためのパラメータである. handler という名前の関数をメイン関数として実行せよ,という意味である.

    • memory_size=128: メモリーは 128MB を最大で使用することを指定している.

    • timeout=core.Duration.seconds(10) タイムアウト時間を 10 秒に設定している. 10 秒以内に関数の実行が終了しなかった場合,エラーが返される.

    • dead_letter_queue_enabled=True: アドバンストな設定なので説明は省略する.

上記のプログラムを実行することで, Lambda 関数がクラウド上に作成される. 早速デプロイしてみよう.

デプロイ

デプロイの手順は,これまでのハンズオンとほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). それぞれの意味を忘れてしまった場合は,ハンズオン 1, 2 に戻って復習していただきたい. シークレットキーの設定も忘れずに ( (#aws_cli_install)).

sh
# プロジェクトのディレクトリに移動
$ cd handson/serverless/lambda

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd handson/serverless/lambda

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイのコマンドが無事に実行されれば, figure_title のような出力が得られるはずである. ここで表示されている SimpleLambda.FunctionName = XXXX の XXXX の文字列は後で使うのでメモしておこう.

CDKデプロイ実行後の出力

AWS コンソールにログインして,デプロイされたスタックを確認してみよう. コンソールから,Lambda のページに行くと figure_title のような画面から Lambda の関数の一覧が確認できる.

Lambda コンソール - 関数の一覧

今回のアプリケーションで作成したのが SimpleLambda で始まるランダムな名前のついた関数だ. 関数の名前をクリックして,詳細を見てみる. すると figure_title のような画面が表示されるはずだ. 先ほどプログラムの中で定義した Python の関数がエディターから確認できる. さらに下の方にスクロールすると,関数の各種設定も確認できる.

Lambda コンソール - 関数の詳細

Lambda で実行されるコードは, Lambda のコンソール画面 (figure_title) のエディターで編集することもできる. デバッグをするときなどは,こちらを直接いじる方が早い場合もある. その場合は, CDK のコードに行った編集を反映させなおすことを忘れずに.

Lambda 関数の実行

それでは,作成した Lambda 関数を実行 (invoke) してみよう. AWS の API を使うことで,関数の実行をスタートすることができる. 今回は, handson/serverless/lambda/invoke_one.py に関数を実行するための簡単なプログラムを提供している. 興味のある読者はコードを読んでもらいたい.

以下のコマンドで,Lambda の関数を実行する. コマンドの XXXX の部分は,先ほどデプロイしたときに SimpleLambda.FunctionName = XXXX で得られた XXXX の文字列で置換する.

sh
$ python invoke_one.py XXXX
$ python invoke_one.py XXXX

すると, "Welcome to Cloud Sushi. Your order is salmon" という出力が得られるはずだ. とてもシンプルではあるが,クラウド上で先ほどの関数が走り,乱数が生成されたうえで,ランダムな寿司ネタが選択されて出力が返されている. このコマンドを何度か打ってみて,実行ごとに異なる寿司ネタが返されることを確認しよう.

さて,このコマンドは,一度につき一回の関数を実行したわけであるが, Lambda の本領は一度に大量のタスクを同時に実行できる点である. そこで,今度は一度に 100 個のタスクを同時に送信してみよう. handson/serverless/lambda/invoke_many.py のスクリプトを使用する.

次のコマンドを実行しよう. XXXX の部分は前述と同様に置き換える. 第二引数の 100 は 100 個のタスクを投入せよ,という意味である.

sh
$ python invoke_many.py XXXX 100
$ python invoke_many.py XXXX 100

すると次のような出力が得られるはずだ.

sh
....................................................................................................
Submitted 100 tasks to Lambda!
....................................................................................................
Submitted 100 tasks to Lambda!

実際に,100 個のタスクが同時に実行されていることを確認しよう. figure_title の画面に戻り, "Monitoring" というタブがあるので,それをクリックする. すると, figure_title のようなグラフが表示されるだろう.

Lambda コンソール - 関数の実行のモニタリング

figure_title のグラフの更新には数分かかることがあるので,なにも表示されない場合は少し待つ.

figure_title で "Invocations" が関数が何度実行されたかを意味している. たしかに 100 回実行されていることがわかる. さらに, "Concurrent executions" は何個のタスクが同時に行われたかを示している. ここでは 96 となっていることから,96 個のタスクが並列的に実行されたことを意味している (これが 100 とならないのは,タスクの開始のコマンドが送られたのが完全には同タイミングではないことに起因する).

このように,非常にシンプルではあるが, Lambda を使うことで,同時並列的に処理を実行することのできるクラウドシステムを簡単に作ることができた.

もしこのようなことを従来的な serverful なクラウドで行おうとした場合,クラスターのスケーリングなど多くのコードを書くことに加えて,いろいろなパラメータを調節する必要がある.

興味がある人は,一気に 1000 個などのジョブを投入してみるとよい. Lambda はそのような大量のリクエストにも対応できることが確認できるだろう. が,あまりやりすぎると Lambda の無料利用枠を超えて料金が発生してしまうので注意.

スタックの削除

最後にスタックを削除しよう. スタックを削除するには,次のコマンドを実行すればよい.

sh
$ cdk destroy
$ cdk destroy

DynamoDB ハンズオン

続いて, DynamoDB の簡単なチュートリアルをやってみよう. ハンズオンのソースコードは GitHub の /handson/serverless/dynamodb に置いてある.

このハンズオンで使用するアプリケーションのスケッチを figure_title に示す. STEP 1 では,AWS CDK を使用して DynamoDB のテーブルを初期化し,デプロイする. 続いて STEP 2 では, API を使用してデータベースのデータの書き込み・読み出し・削除などの操作を練習する.

DynamoDB チュートリアルの概要

このハンズオンは,基本的に AWS DynamoDB の無料枠 の範囲内で実行できる.

handson/serverless/dynamodb/app.py にデプロイするプログラムが書かれている. 中身を見てみよう.

python
class SimpleDynamoDb(core.Stack):
    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        table = ddb.Table(
            self, "SimpleTable",
            #
            partition_key=ddb.Attribute(
                name="item_id",
                type=ddb.AttributeType.STRING
            ),
            #
            billing_mode=ddb.BillingMode.PAY_PER_REQUEST,
            #
            removal_policy=core.RemovalPolicy.DESTROY
        )
class SimpleDynamoDb(core.Stack):
    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        table = ddb.Table(
            self, "SimpleTable",
            #
            partition_key=ddb.Attribute(
                name="item_id",
                type=ddb.AttributeType.STRING
            ),
            #
            billing_mode=ddb.BillingMode.PAY_PER_REQUEST,
            #
            removal_policy=core.RemovalPolicy.DESTROY
        )

このコードで,最低限の設定がなされた空の DynamoDB テーブルが作成される. それぞれのパラメータの意味を簡単に解説しよう.

  • partition_key: すべての DynamoDB テーブルには Partition key が定義されていなければならない. Partition key とは,テーブル内の要素 (レコード) ごとに存在する固有の ID のことである. 同一の Partition key をもった要素がテーブルの中に二つ以上存在することはできない (注: Sort Key を使用している場合は除く.詳しくは 公式ドキュメンテーション "Core Components of Amazon DynamoDB" 参照). また, Partition key が定義されていない要素はテーブルの中に存在することはできない. ここでは, Partition key に item_id という名前をつけている.

  • billing_mode: ddb.BillingMode.PAY_PER_REQUEST を指定することで, On-demand Capacity Mode の DynamoDB が作成される. ほかに PROVISIONED というモードがあるが,これはかなり高度なケースを除いて使用しないだろう.

  • removal_policy: CloudFormation のスタックが消去されたときに, DynamoDB も一緒に消去されるかどうかを指定する. このコードでは DESTROY を選んでいるので,すべて消去される. ほかのオプションを選択すると,スタックを消去しても DynamoDB のバックアップを残す,などの動作を定義することができる.

デプロイ

デプロイの手順は,これまでのハンズオンとほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). シークレットキーの設定も忘れずに ( (#aws_cli_install)).

sh
# プロジェクトのディレクトリに移動
$ cd handson/serverless/dynamodb

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd handson/serverless/dynamodb

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイのコマンドが無事に実行されれば, figure_title のような出力が得られるはずである. ここで表示されている SimpleDynamoDb.TableName = XXXX の XXXX の文字列は後で使うのでメモしておこう.

CDKデプロイ実行後の出力

AWS コンソールにログインして,デプロイされたスタックを確認してみよう. コンソールから, DynamoDB のページに行き,左のメニューバーから "Tables" を選択する. すると, figure_title のような画面からテーブルの一覧が確認できる.

DynamoDB のコンソール (テーブルの一覧)

今回のアプリケーションで作成したのが SimpleDynamoDb で始まるランダムな名前のついたテーブルだ. テーブルの名前をクリックして,詳細を見てみる. すると figure_title のような画面が表示されるはずだ. "Items" のタブをクリックすると,テーブルの中のレコードを確認できる. 現時点ではなにもデータを書き込んでいないので,空である.

DynamoDB のコンソール (テーブルの詳細画面)

データの読み書き

それでは, デプロイ で作ったテーブルを使ってデータの読み書きを実践してみよう. ここでは Python と boto3 ライブラリを用いた方法を紹介する.

まずは,テーブルに新しい要素を追加してみよう. ハンズオンのディレクトリにある simple_write.py を開いてみよう. 中には次のような関数が書かれている.

python
import boto3
from uuid import uuid4
ddb = boto3.resource('dynamodb')

def write_item(table_name):
    table = ddb.Table(table_name)
    table.put_item(
    Item={
        'item_id': str(uuid4()),
        'first_name': 'John',
        'last_name': 'Doe',
        'age': 25,
        }
    )
import boto3
from uuid import uuid4
ddb = boto3.resource('dynamodb')

def write_item(table_name):
    table = ddb.Table(table_name)
    table.put_item(
    Item={
        'item_id': str(uuid4()),
        'first_name': 'John',
        'last_name': 'Doe',
        'age': 25,
        }
    )

コードを上から読んでいくと,まず最初に boto3 ライブラリをインポートし, dynamodb のリソースを呼び出している. write_item() 関数は, DynamoDB のテーブルの名前 (上で見た SimpleDynamoDb-XXXX) を引数として受け取る. そして, put_item() メソッドを呼ぶことで,新しいアイテムを DB に書き込んでいる. アイテムには item_id, first_name, last_name, age の 4 つの属性が定義されている. ここで, item_id は先ほど説明した Partition key に相当しており, UUID4 を用いたランダムな文字列を割り当てている.

では, simple_write.py を実行してみよう. "XXXX" の部分を自分がデプロイしたテーブルの名前 (SimpleDynamoDb で始まる文字列) に置き換えたうえで,次のコマンドを実行する.

sh
$ python simple_write.py XXXX
$ python simple_write.py XXXX

新しい要素が正しく書き込めたか, AWS コンソールから確認してみよう. figure_title と同じ手順で,テーブルの中身の要素の一覧を表示する. すると figure_title のように,期待通り新しい要素が見つかるだろう.

DynamoDB に新しい要素が追加されたことを確認

boto3 を使ってテーブルから要素を読みだすことも可能である. ハンズオンのディレクトリにある simple_read.py を見てみよう.

python
import boto3
ddb = boto3.resource('dynamodb')

def scan_table(table_name):
    table = ddb.Table(table_name)
    items = table.scan().get("Items")
    print(items)
import boto3
ddb = boto3.resource('dynamodb')

def scan_table(table_name):
    table = ddb.Table(table_name)
    items = table.scan().get("Items")
    print(items)

table.scan().get("Items") によって,テーブルの中にあるすべての要素を読みだしている.

次のコマンドで,このスクリプトを実行してみよう ("XXXX" の部分を正しく置き換えることを忘れずに).

sh
$ python simple_read.py XXXX
$ python simple_read.py XXXX

先ほど書き込んだ要素が出力されることを確認しよう.

大量のデータの読み書き

DynamoDB の利点は,最初に述べたとおり,負荷に応じて自在にその処理能力を拡大できる点である.

そこで,ここでは一度に大量のデータを書き込む場合をシミュレートしてみよう. batch_rw.py に,一度に大量の書き込みを実行するためのプログラムが書いてある.

次のコマンドを実行してみよう (XXXX は自分のテーブルの名前に置き換える).

sh
$ python batch_rw.py XXXX write 1000
$ python batch_rw.py XXXX write 1000

このコマンドを実行することで,ランダムなデータが 1000 個データベースに書き込まれる.

さらに,データベースの検索をかけてみよう. 今回書き込んだデータには age という属性に 1 から 50 のランダムな整数が割り当てられている. age が 2 以下であるような要素だけを検索し拾ってくるには,次のコマンドを実行すればよい.

sh
$ python batch_rw.py XXXX search_under_age 2
$ python batch_rw.py XXXX search_under_age 2

上の 2 つのコマンドを何回か繰り返し実行してみて,データベースに負荷をかけてみよう. とくに大きな遅延なく結果が返ってくることが確認できるだろう.

スタックの削除

DynamoDB で十分に遊ぶことができたら,忘れずにスタックを削除しよう.

これまでのハンズオンと同様,スタックを削除するには,次のコマンドを実行すればよい.

sh
$ cdk destroy
$ cdk destroy

S3 ハンズオン

最後に, S3 の簡単なチュートリアルを紹介する. ハンズオンのソースコードは GitHub の handson/serverless/s3 に置いてある.

figure_title が今回提供する S3 チュートリアルの概要である. STEP 1 として, AWS CDK を用いて S3 に新しい空のバケット (Bucket) を作成する. 続いて STEP 2 では,データのアップロード・ダウンロードの方法を解説する.

S3 チュートリアルの概要

このハンズオンは,基本的に S3 の無料枠 の範囲内で実行することができる.

app.py にデプロイするプログラムが書かれている. 中身を見てみよう.

python
class SimpleS3(core.Stack):
    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        # S3 bucket to store data
        bucket = s3.Bucket(
            self, "bucket",
            removal_policy=core.RemovalPolicy.DESTROY,
            auto_delete_objects=True,
        )
class SimpleS3(core.Stack):
    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        # S3 bucket to store data
        bucket = s3.Bucket(
            self, "bucket",
            removal_policy=core.RemovalPolicy.DESTROY,
            auto_delete_objects=True,
        )

s3.Bucket() を呼ぶことによって空のバケットが新規に作成される. 上記のコードだと,バケットの名前は自動生成される. もし,自分の指定した名前を与えたい場合は, bucket_name というパラメータを指定すればよい. その際, バケットの名前はユニークでなければならない (i.e. AWS のデプロイが行われるリージョン内で名前の重複がない) 点に注意しよう. もし,同じ名前のバケットが既に存在する場合はエラーが返ってくる.

デフォルトでは, CloudFormation スタックが削除されたとき, S3 バケットとその中に保存されたファイルは削除されない. これは,大切なデータを誤って消してしまうことを防止するための安全策である. cdk destroy を実行したときにバケットも含めてすべて削除されるようにするには, removal_policy=core.RemovalPolicy.DESTROY, auto_delete_objects=True とパラメータを設定する. 結果もよく理解したうえで,自分の用途にあった適切なパラメータを設定しよう.

デプロイ

デプロイの手順は,これまでのハンズオンとほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). シークレットキーの設定も忘れずに ( (#aws_cli_install)).

sh
# プロジェクトのディレクトリに移動
$ cd handson/serverless/s3

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd handson/serverless/s3

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイを実行すると, figure_title のような出力が得られるはずである. ここで表示されている SimpleS3.BucketName = XXXX が,新しく作られたバケットの名前である (今回提供しているコードを使うとランダムな名前がバケットに割り当てられる). これはあとで使うのでメモしておこう.

デプロイ実行後の出力

データの読み書き

スタックのデプロイが完了したら,早速バケットにデータをアップロードしてみよう.

まずは,以下のコマンドを実行して, tmp.txt という仮のファイルを生成する.

sh
$ echo "Hello world!" >> tmp.txt
$ echo "Hello world!" >> tmp.txt

ハンズオンのディレクトリにある simple_s3.pyboto3 ライブラリを使用した S3 のファイルのアップロード・ダウンロードのスクリプトが書いてある. simple_s3.py を使って,上で作成した tmp.txt を以下のコマンドによりバケットにアップロードする. XXXX のところは,自分自身のバケットの名前で置き換えること.

sh
$ python simple_s3.py XXXX upload tmp.txt
$ python simple_s3.py XXXX upload tmp.txt

simple_s3.py のアップロードを担当している部分を以下に抜粋する.

python
def upload_file(bucket_name, filename, key=None):
    bucket = s3.Bucket(bucket_name)

    if key is None:
        key = os.path.basename(filename)

    bucket.upload_file(filename, key)
def upload_file(bucket_name, filename, key=None):
    bucket = s3.Bucket(bucket_name)

    if key is None:
        key = os.path.basename(filename)

    bucket.upload_file(filename, key)

bucket = s3.Bucket(bucket_name) の行で Bucket() オブジェクトを呼び出している. そして, upload_file() メソッドを呼ぶことでファイルのアップロードを実行している.

S3 においてファイルの識別子として使われるのが Key である. これは,従来的なファイルシステムにおけるパス (Path) と相同な概念で,それぞれのファイルに固有な Key が割り当てられる必要がある. Key という呼び方は, S3 が Object storage と呼ばれるシステムに立脚していることに由来する. --key のオプションを追加して simple_s3.py を実行することで, Key を指定してアップロードを実行することができる.

sh
$ python simple_s3.py XXXX upload tmp.txt --key a/b/tmp.txt
$ python simple_s3.py XXXX upload tmp.txt --key a/b/tmp.txt

ここではアップロードされたファイルに a/b/tmp.txt という Key を割り当てている.

ここまでコマンドを実行し終えたところで,一度 AWS コンソールに行き S3 の中身を確認してみよう. S3 のコンソールに行くと,バケットの一覧が見つかるはずである. その中から, simples3-bucket から始まるランダムな名前のついたバケットを探し,クリックする. するとバケットの中に含まれるファイルの一覧が表示される (figure_title).

S3 バケットの中のファイル一覧

ここで実行した 2 つのコマンドによって, tmp.txt というファイルと, a/b/tmp.txt というファイルが見つかることに注目しよう. 従来的なファイルシステムと似た体験を提供するため, S3 では Key が "/" (スラッシュ) によって区切られていた場合,ツリー状の階層構造によってファイルを管理することができる.

オブジェクトストレージには本来ディレクトリという概念はない. 上で紹介した "/" による階層づけはあくまでユーザー体験向上の目的のお化粧的な機能である.

次に,バケットからファイルのダウンロードを実行してみよう. simple_s3.py を使って,以下のコマンドを実行すればよい. XXXX のところは,自分自身のバケットの名前で置き換えること.

sh
$ python simple_s3.py XXXX download tmp.txt
$ python simple_s3.py XXXX download tmp.txt

simple_s3.py のダウンロードを担当している部分を以下に抜粋する.

python
def download_file(bucket_name, key, filename=None):
    bucket = s3.Bucket(bucket_name)

    if filename is None:
        filename = os.path.basename(key)

    bucket.download_file(key, filename)
def download_file(bucket_name, key, filename=None):
    bucket = s3.Bucket(bucket_name)

    if filename is None:
        filename = os.path.basename(key)

    bucket.download_file(key, filename)

S3 からのダウンロードはシンプルで, download_file() メソッドを使って,ダウンロードしたい対象の Key を指定すればよい. ローカルのコンピュータでの保存先のパスを 2 個目の引数として渡している.

スタックの削除

以上のハンズオンで, S3 の一番基本的な使い方を紹介した. ここまでのハンズオンが理解できたら,忘れずにスタックを削除しよう. これまでのハンズオンと同様,スタックを削除するには,次のコマンドを実行すればよい.

sh
$ cdk destroy
$ cdk destroy
]]>
Hands-on #5: サーバーレス入門

前章ではサーバーレスアーキテクチャの概要の説明を行った. 本章では,ハンズオン形式でサーバーレスクラウドを実際に動かしながら,具体的な使用方法を学んでいこう. 今回のハンズオンでは Lambda, S3, DynamoDB の三つのサーバーレスクラウドの構成要素に触れていく. それぞれについて,短いチュートリアルを用意してある.

Lambda ハンズオン

まずは, Lambda を実際に動かしてみよう. ハンズオンのソースコードは GitHub の handson/serverless/lambda に置いてある.

このハンズオンで使用するアプリケーションのスケッチを figure_title に示す. STEP 1 では,AWS CDK を使用して Python で書かれたコードを Lambda に登録する. 続いて STEP 2 では, Invoke API を使用して,同時にいくつもの Lambda を起動し,並列な計算を行う. Lambda のワークフローを体験する目的で最小限の設定である.

Lambda チュートリアルの概要

このハンズオンは,基本的に AWS Lambda の無料枠 の範囲内で実行することができる.

app.py にデプロイするプログラムが書かれている. 中身を見てみよう.

python
#
FUNC = """
import time
from random import choice, randint
def handler(event, context):
    time.sleep(randint(2,5))
    sushi = ["salmon", "tuna", "squid"]
    message = "Welcome to Cloud Sushi. Your order is " + choice(sushi)
    print(message)
    return message
"""

class SimpleLambda(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        handler = _lambda.Function(
            self, 'LambdaHandler',
            runtime=_lambda.Runtime.PYTHON_3_7,
            code=_lambda.Code.from_inline(FUNC),
            handler="index.handler",
            memory_size=128,
            timeout=core.Duration.seconds(10),
            dead_letter_queue_enabled=True,
        )
#
FUNC = """
import time
from random import choice, randint
def handler(event, context):
    time.sleep(randint(2,5))
    sushi = ["salmon", "tuna", "squid"]
    message = "Welcome to Cloud Sushi. Your order is " + choice(sushi)
    print(message)
    return message
"""

class SimpleLambda(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        handler = _lambda.Function(
            self, 'LambdaHandler',
            runtime=_lambda.Runtime.PYTHON_3_7,
            code=_lambda.Code.from_inline(FUNC),
            handler="index.handler",
            memory_size=128,
            timeout=core.Duration.seconds(10),
            dead_letter_queue_enabled=True,
        )
  • ここで, Lambda で実行されるべき関数を定義している. これは非常に単純な関数で,2-5 秒のランダムな時間スリープした後,["salmon", "tuna", "squid"] のいずれかの文字列をランダムに選択し, "Welcome to Cloud Sushi. Your order is XXXX" (XXXX は選ばれた寿司のネタ) というメッセージをリターンする.

  • 次に, Lambda に <1> で書いた関数を配置している. パラメータの意味は,文字どおりの意味なので難しくはないが,以下に解説する.

    • runtime=_lambda.Runtime.PYTHON_3_7: ここでは, Python3.7 を使って上記で定義された関数を実行せよ,と指定している. Python3.7 のほかに, Node.js, Java, Ruby, Go などの言語を指定することが可能である.

    • code=_lambda.Code.from_inline(FUNC): 実行されるべき関数が書かれたコードを指定する. ここでは, FUNC=... で定義した文字列を渡しているが,文字列以外にもファイルのパスを渡すことも可能である.

    • handler="index.handler": これは,コードの中にいくつかのサブ関数が含まれているときに,メインとサブを区別するためのパラメータである. handler という名前の関数をメイン関数として実行せよ,という意味である.

    • memory_size=128: メモリーは 128MB を最大で使用することを指定している.

    • timeout=core.Duration.seconds(10) タイムアウト時間を 10 秒に設定している. 10 秒以内に関数の実行が終了しなかった場合,エラーが返される.

    • dead_letter_queue_enabled=True: アドバンストな設定なので説明は省略する.

上記のプログラムを実行することで, Lambda 関数がクラウド上に作成される. 早速デプロイしてみよう.

デプロイ

デプロイの手順は,これまでのハンズオンとほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). それぞれの意味を忘れてしまった場合は,ハンズオン 1, 2 に戻って復習していただきたい. シークレットキーの設定も忘れずに ( (#aws_cli_install)).

sh
# プロジェクトのディレクトリに移動
$ cd handson/serverless/lambda

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd handson/serverless/lambda

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイのコマンドが無事に実行されれば, figure_title のような出力が得られるはずである. ここで表示されている SimpleLambda.FunctionName = XXXX の XXXX の文字列は後で使うのでメモしておこう.

CDKデプロイ実行後の出力

AWS コンソールにログインして,デプロイされたスタックを確認してみよう. コンソールから,Lambda のページに行くと figure_title のような画面から Lambda の関数の一覧が確認できる.

Lambda コンソール - 関数の一覧

今回のアプリケーションで作成したのが SimpleLambda で始まるランダムな名前のついた関数だ. 関数の名前をクリックして,詳細を見てみる. すると figure_title のような画面が表示されるはずだ. 先ほどプログラムの中で定義した Python の関数がエディターから確認できる. さらに下の方にスクロールすると,関数の各種設定も確認できる.

Lambda コンソール - 関数の詳細

Lambda で実行されるコードは, Lambda のコンソール画面 (figure_title) のエディターで編集することもできる. デバッグをするときなどは,こちらを直接いじる方が早い場合もある. その場合は, CDK のコードに行った編集を反映させなおすことを忘れずに.

Lambda 関数の実行

それでは,作成した Lambda 関数を実行 (invoke) してみよう. AWS の API を使うことで,関数の実行をスタートすることができる. 今回は, handson/serverless/lambda/invoke_one.py に関数を実行するための簡単なプログラムを提供している. 興味のある読者はコードを読んでもらいたい.

以下のコマンドで,Lambda の関数を実行する. コマンドの XXXX の部分は,先ほどデプロイしたときに SimpleLambda.FunctionName = XXXX で得られた XXXX の文字列で置換する.

sh
$ python invoke_one.py XXXX
$ python invoke_one.py XXXX

すると, "Welcome to Cloud Sushi. Your order is salmon" という出力が得られるはずだ. とてもシンプルではあるが,クラウド上で先ほどの関数が走り,乱数が生成されたうえで,ランダムな寿司ネタが選択されて出力が返されている. このコマンドを何度か打ってみて,実行ごとに異なる寿司ネタが返されることを確認しよう.

さて,このコマンドは,一度につき一回の関数を実行したわけであるが, Lambda の本領は一度に大量のタスクを同時に実行できる点である. そこで,今度は一度に 100 個のタスクを同時に送信してみよう. handson/serverless/lambda/invoke_many.py のスクリプトを使用する.

次のコマンドを実行しよう. XXXX の部分は前述と同様に置き換える. 第二引数の 100 は 100 個のタスクを投入せよ,という意味である.

sh
$ python invoke_many.py XXXX 100
$ python invoke_many.py XXXX 100

すると次のような出力が得られるはずだ.

sh
....................................................................................................
Submitted 100 tasks to Lambda!
....................................................................................................
Submitted 100 tasks to Lambda!

実際に,100 個のタスクが同時に実行されていることを確認しよう. figure_title の画面に戻り, "Monitoring" というタブがあるので,それをクリックする. すると, figure_title のようなグラフが表示されるだろう.

Lambda コンソール - 関数の実行のモニタリング

figure_title のグラフの更新には数分かかることがあるので,なにも表示されない場合は少し待つ.

figure_title で "Invocations" が関数が何度実行されたかを意味している. たしかに 100 回実行されていることがわかる. さらに, "Concurrent executions" は何個のタスクが同時に行われたかを示している. ここでは 96 となっていることから,96 個のタスクが並列的に実行されたことを意味している (これが 100 とならないのは,タスクの開始のコマンドが送られたのが完全には同タイミングではないことに起因する).

このように,非常にシンプルではあるが, Lambda を使うことで,同時並列的に処理を実行することのできるクラウドシステムを簡単に作ることができた.

もしこのようなことを従来的な serverful なクラウドで行おうとした場合,クラスターのスケーリングなど多くのコードを書くことに加えて,いろいろなパラメータを調節する必要がある.

興味がある人は,一気に 1000 個などのジョブを投入してみるとよい. Lambda はそのような大量のリクエストにも対応できることが確認できるだろう. が,あまりやりすぎると Lambda の無料利用枠を超えて料金が発生してしまうので注意.

スタックの削除

最後にスタックを削除しよう. スタックを削除するには,次のコマンドを実行すればよい.

sh
$ cdk destroy
$ cdk destroy

DynamoDB ハンズオン

続いて, DynamoDB の簡単なチュートリアルをやってみよう. ハンズオンのソースコードは GitHub の /handson/serverless/dynamodb に置いてある.

このハンズオンで使用するアプリケーションのスケッチを figure_title に示す. STEP 1 では,AWS CDK を使用して DynamoDB のテーブルを初期化し,デプロイする. 続いて STEP 2 では, API を使用してデータベースのデータの書き込み・読み出し・削除などの操作を練習する.

DynamoDB チュートリアルの概要

このハンズオンは,基本的に AWS DynamoDB の無料枠 の範囲内で実行できる.

handson/serverless/dynamodb/app.py にデプロイするプログラムが書かれている. 中身を見てみよう.

python
class SimpleDynamoDb(core.Stack):
    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        table = ddb.Table(
            self, "SimpleTable",
            #
            partition_key=ddb.Attribute(
                name="item_id",
                type=ddb.AttributeType.STRING
            ),
            #
            billing_mode=ddb.BillingMode.PAY_PER_REQUEST,
            #
            removal_policy=core.RemovalPolicy.DESTROY
        )
class SimpleDynamoDb(core.Stack):
    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        table = ddb.Table(
            self, "SimpleTable",
            #
            partition_key=ddb.Attribute(
                name="item_id",
                type=ddb.AttributeType.STRING
            ),
            #
            billing_mode=ddb.BillingMode.PAY_PER_REQUEST,
            #
            removal_policy=core.RemovalPolicy.DESTROY
        )

このコードで,最低限の設定がなされた空の DynamoDB テーブルが作成される. それぞれのパラメータの意味を簡単に解説しよう.

  • partition_key: すべての DynamoDB テーブルには Partition key が定義されていなければならない. Partition key とは,テーブル内の要素 (レコード) ごとに存在する固有の ID のことである. 同一の Partition key をもった要素がテーブルの中に二つ以上存在することはできない (注: Sort Key を使用している場合は除く.詳しくは 公式ドキュメンテーション "Core Components of Amazon DynamoDB" 参照). また, Partition key が定義されていない要素はテーブルの中に存在することはできない. ここでは, Partition key に item_id という名前をつけている.

  • billing_mode: ddb.BillingMode.PAY_PER_REQUEST を指定することで, On-demand Capacity Mode の DynamoDB が作成される. ほかに PROVISIONED というモードがあるが,これはかなり高度なケースを除いて使用しないだろう.

  • removal_policy: CloudFormation のスタックが消去されたときに, DynamoDB も一緒に消去されるかどうかを指定する. このコードでは DESTROY を選んでいるので,すべて消去される. ほかのオプションを選択すると,スタックを消去しても DynamoDB のバックアップを残す,などの動作を定義することができる.

デプロイ

デプロイの手順は,これまでのハンズオンとほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). シークレットキーの設定も忘れずに ( (#aws_cli_install)).

sh
# プロジェクトのディレクトリに移動
$ cd handson/serverless/dynamodb

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd handson/serverless/dynamodb

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイのコマンドが無事に実行されれば, figure_title のような出力が得られるはずである. ここで表示されている SimpleDynamoDb.TableName = XXXX の XXXX の文字列は後で使うのでメモしておこう.

CDKデプロイ実行後の出力

AWS コンソールにログインして,デプロイされたスタックを確認してみよう. コンソールから, DynamoDB のページに行き,左のメニューバーから "Tables" を選択する. すると, figure_title のような画面からテーブルの一覧が確認できる.

DynamoDB のコンソール (テーブルの一覧)

今回のアプリケーションで作成したのが SimpleDynamoDb で始まるランダムな名前のついたテーブルだ. テーブルの名前をクリックして,詳細を見てみる. すると figure_title のような画面が表示されるはずだ. "Items" のタブをクリックすると,テーブルの中のレコードを確認できる. 現時点ではなにもデータを書き込んでいないので,空である.

DynamoDB のコンソール (テーブルの詳細画面)

データの読み書き

それでは, デプロイ で作ったテーブルを使ってデータの読み書きを実践してみよう. ここでは Python と boto3 ライブラリを用いた方法を紹介する.

まずは,テーブルに新しい要素を追加してみよう. ハンズオンのディレクトリにある simple_write.py を開いてみよう. 中には次のような関数が書かれている.

python
import boto3
from uuid import uuid4
ddb = boto3.resource('dynamodb')

def write_item(table_name):
    table = ddb.Table(table_name)
    table.put_item(
    Item={
        'item_id': str(uuid4()),
        'first_name': 'John',
        'last_name': 'Doe',
        'age': 25,
        }
    )
import boto3
from uuid import uuid4
ddb = boto3.resource('dynamodb')

def write_item(table_name):
    table = ddb.Table(table_name)
    table.put_item(
    Item={
        'item_id': str(uuid4()),
        'first_name': 'John',
        'last_name': 'Doe',
        'age': 25,
        }
    )

コードを上から読んでいくと,まず最初に boto3 ライブラリをインポートし, dynamodb のリソースを呼び出している. write_item() 関数は, DynamoDB のテーブルの名前 (上で見た SimpleDynamoDb-XXXX) を引数として受け取る. そして, put_item() メソッドを呼ぶことで,新しいアイテムを DB に書き込んでいる. アイテムには item_id, first_name, last_name, age の 4 つの属性が定義されている. ここで, item_id は先ほど説明した Partition key に相当しており, UUID4 を用いたランダムな文字列を割り当てている.

では, simple_write.py を実行してみよう. "XXXX" の部分を自分がデプロイしたテーブルの名前 (SimpleDynamoDb で始まる文字列) に置き換えたうえで,次のコマンドを実行する.

sh
$ python simple_write.py XXXX
$ python simple_write.py XXXX

新しい要素が正しく書き込めたか, AWS コンソールから確認してみよう. figure_title と同じ手順で,テーブルの中身の要素の一覧を表示する. すると figure_title のように,期待通り新しい要素が見つかるだろう.

DynamoDB に新しい要素が追加されたことを確認

boto3 を使ってテーブルから要素を読みだすことも可能である. ハンズオンのディレクトリにある simple_read.py を見てみよう.

python
import boto3
ddb = boto3.resource('dynamodb')

def scan_table(table_name):
    table = ddb.Table(table_name)
    items = table.scan().get("Items")
    print(items)
import boto3
ddb = boto3.resource('dynamodb')

def scan_table(table_name):
    table = ddb.Table(table_name)
    items = table.scan().get("Items")
    print(items)

table.scan().get("Items") によって,テーブルの中にあるすべての要素を読みだしている.

次のコマンドで,このスクリプトを実行してみよう ("XXXX" の部分を正しく置き換えることを忘れずに).

sh
$ python simple_read.py XXXX
$ python simple_read.py XXXX

先ほど書き込んだ要素が出力されることを確認しよう.

大量のデータの読み書き

DynamoDB の利点は,最初に述べたとおり,負荷に応じて自在にその処理能力を拡大できる点である.

そこで,ここでは一度に大量のデータを書き込む場合をシミュレートしてみよう. batch_rw.py に,一度に大量の書き込みを実行するためのプログラムが書いてある.

次のコマンドを実行してみよう (XXXX は自分のテーブルの名前に置き換える).

sh
$ python batch_rw.py XXXX write 1000
$ python batch_rw.py XXXX write 1000

このコマンドを実行することで,ランダムなデータが 1000 個データベースに書き込まれる.

さらに,データベースの検索をかけてみよう. 今回書き込んだデータには age という属性に 1 から 50 のランダムな整数が割り当てられている. age が 2 以下であるような要素だけを検索し拾ってくるには,次のコマンドを実行すればよい.

sh
$ python batch_rw.py XXXX search_under_age 2
$ python batch_rw.py XXXX search_under_age 2

上の 2 つのコマンドを何回か繰り返し実行してみて,データベースに負荷をかけてみよう. とくに大きな遅延なく結果が返ってくることが確認できるだろう.

スタックの削除

DynamoDB で十分に遊ぶことができたら,忘れずにスタックを削除しよう.

これまでのハンズオンと同様,スタックを削除するには,次のコマンドを実行すればよい.

sh
$ cdk destroy
$ cdk destroy

S3 ハンズオン

最後に, S3 の簡単なチュートリアルを紹介する. ハンズオンのソースコードは GitHub の handson/serverless/s3 に置いてある.

figure_title が今回提供する S3 チュートリアルの概要である. STEP 1 として, AWS CDK を用いて S3 に新しい空のバケット (Bucket) を作成する. 続いて STEP 2 では,データのアップロード・ダウンロードの方法を解説する.

S3 チュートリアルの概要

このハンズオンは,基本的に S3 の無料枠 の範囲内で実行することができる.

app.py にデプロイするプログラムが書かれている. 中身を見てみよう.

python
class SimpleS3(core.Stack):
    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        # S3 bucket to store data
        bucket = s3.Bucket(
            self, "bucket",
            removal_policy=core.RemovalPolicy.DESTROY,
            auto_delete_objects=True,
        )
class SimpleS3(core.Stack):
    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        # S3 bucket to store data
        bucket = s3.Bucket(
            self, "bucket",
            removal_policy=core.RemovalPolicy.DESTROY,
            auto_delete_objects=True,
        )

s3.Bucket() を呼ぶことによって空のバケットが新規に作成される. 上記のコードだと,バケットの名前は自動生成される. もし,自分の指定した名前を与えたい場合は, bucket_name というパラメータを指定すればよい. その際, バケットの名前はユニークでなければならない (i.e. AWS のデプロイが行われるリージョン内で名前の重複がない) 点に注意しよう. もし,同じ名前のバケットが既に存在する場合はエラーが返ってくる.

デフォルトでは, CloudFormation スタックが削除されたとき, S3 バケットとその中に保存されたファイルは削除されない. これは,大切なデータを誤って消してしまうことを防止するための安全策である. cdk destroy を実行したときにバケットも含めてすべて削除されるようにするには, removal_policy=core.RemovalPolicy.DESTROY, auto_delete_objects=True とパラメータを設定する. 結果もよく理解したうえで,自分の用途にあった適切なパラメータを設定しよう.

デプロイ

デプロイの手順は,これまでのハンズオンとほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). シークレットキーの設定も忘れずに ( (#aws_cli_install)).

sh
# プロジェクトのディレクトリに移動
$ cd handson/serverless/s3

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd handson/serverless/s3

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイを実行すると, figure_title のような出力が得られるはずである. ここで表示されている SimpleS3.BucketName = XXXX が,新しく作られたバケットの名前である (今回提供しているコードを使うとランダムな名前がバケットに割り当てられる). これはあとで使うのでメモしておこう.

デプロイ実行後の出力

データの読み書き

スタックのデプロイが完了したら,早速バケットにデータをアップロードしてみよう.

まずは,以下のコマンドを実行して, tmp.txt という仮のファイルを生成する.

sh
$ echo "Hello world!" >> tmp.txt
$ echo "Hello world!" >> tmp.txt

ハンズオンのディレクトリにある simple_s3.pyboto3 ライブラリを使用した S3 のファイルのアップロード・ダウンロードのスクリプトが書いてある. simple_s3.py を使って,上で作成した tmp.txt を以下のコマンドによりバケットにアップロードする. XXXX のところは,自分自身のバケットの名前で置き換えること.

sh
$ python simple_s3.py XXXX upload tmp.txt
$ python simple_s3.py XXXX upload tmp.txt

simple_s3.py のアップロードを担当している部分を以下に抜粋する.

python
def upload_file(bucket_name, filename, key=None):
    bucket = s3.Bucket(bucket_name)

    if key is None:
        key = os.path.basename(filename)

    bucket.upload_file(filename, key)
def upload_file(bucket_name, filename, key=None):
    bucket = s3.Bucket(bucket_name)

    if key is None:
        key = os.path.basename(filename)

    bucket.upload_file(filename, key)

bucket = s3.Bucket(bucket_name) の行で Bucket() オブジェクトを呼び出している. そして, upload_file() メソッドを呼ぶことでファイルのアップロードを実行している.

S3 においてファイルの識別子として使われるのが Key である. これは,従来的なファイルシステムにおけるパス (Path) と相同な概念で,それぞれのファイルに固有な Key が割り当てられる必要がある. Key という呼び方は, S3 が Object storage と呼ばれるシステムに立脚していることに由来する. --key のオプションを追加して simple_s3.py を実行することで, Key を指定してアップロードを実行することができる.

sh
$ python simple_s3.py XXXX upload tmp.txt --key a/b/tmp.txt
$ python simple_s3.py XXXX upload tmp.txt --key a/b/tmp.txt

ここではアップロードされたファイルに a/b/tmp.txt という Key を割り当てている.

ここまでコマンドを実行し終えたところで,一度 AWS コンソールに行き S3 の中身を確認してみよう. S3 のコンソールに行くと,バケットの一覧が見つかるはずである. その中から, simples3-bucket から始まるランダムな名前のついたバケットを探し,クリックする. するとバケットの中に含まれるファイルの一覧が表示される (figure_title).

S3 バケットの中のファイル一覧

ここで実行した 2 つのコマンドによって, tmp.txt というファイルと, a/b/tmp.txt というファイルが見つかることに注目しよう. 従来的なファイルシステムと似た体験を提供するため, S3 では Key が "/" (スラッシュ) によって区切られていた場合,ツリー状の階層構造によってファイルを管理することができる.

オブジェクトストレージには本来ディレクトリという概念はない. 上で紹介した "/" による階層づけはあくまでユーザー体験向上の目的のお化粧的な機能である.

次に,バケットからファイルのダウンロードを実行してみよう. simple_s3.py を使って,以下のコマンドを実行すればよい. XXXX のところは,自分自身のバケットの名前で置き換えること.

sh
$ python simple_s3.py XXXX download tmp.txt
$ python simple_s3.py XXXX download tmp.txt

simple_s3.py のダウンロードを担当している部分を以下に抜粋する.

python
def download_file(bucket_name, key, filename=None):
    bucket = s3.Bucket(bucket_name)

    if filename is None:
        filename = os.path.basename(key)

    bucket.download_file(key, filename)
def download_file(bucket_name, key, filename=None):
    bucket = s3.Bucket(bucket_name)

    if filename is None:
        filename = os.path.basename(key)

    bucket.download_file(key, filename)

S3 からのダウンロードはシンプルで, download_file() メソッドを使って,ダウンロードしたい対象の Key を指定すればよい. ローカルのコンピュータでの保存先のパスを 2 個目の引数として渡している.

スタックの削除

以上のハンズオンで, S3 の一番基本的な使い方を紹介した. ここまでのハンズオンが理解できたら,忘れずにスタックを削除しよう. これまでのハンズオンと同様,スタックを削除するには,次のコマンドを実行すればよい.

sh
$ cdk destroy
$ cdk destroy
]]>
<![CDATA[はじめに ]]> https://note.toshiki.dev/development/aws/ https://note.toshiki.dev/development/aws/ Thu, 01 Jul 2021 00:00:00 GMT はじめに

本書の目的・内容

本書は,東京大学計数工学科で 2021 年度 S1/S2 タームに開講されている"システム情報工学特論"の講義資料として作成された.

本書の目的は,クラウドの初心者を対象とし,クラウドの基礎的な知識・概念を解説する. また, Amazon Web Services (以下, AWS) の提供するクラウド環境を実例として,具体的なクラウドの利用方法をハンズオンを通して学ぶ.

とくに,科学・エンジニアリングの学生を対象として,研究などの目的でクラウドを利用するための実践的な手順を紹介する. 知識・理論の説明は最小限に留め,実践を行う中で必要な概念の解説を行う予定である. 読者が今後,研究などでクラウドを利用する際の,足がかりとなれば本書の目的は十分達成されたことになる.

本書は以下のような三部構成になっている.

本書の構成
テーマハンズオン

第一部 (1章-4章)

クラウドの基礎

  • AWSに自分のサーバーを立ち上げる

第二部 (5章-9章)

クラウドを活用した機械学習

  • AWS と Jupyter を使って始めるディープラーニング

  • スケーラブルな自動質問回答ボットを作る

  • 並列化されたハイパーパラメータサーチの実装

第三部 (10章-13章)

サーバーレスアーキテクチャ入門

  • Lambda, DynamoDB, S3 の演習

  • 俳句を投稿する SNS "Bashoutter" を作る

第一部は,クラウドの基礎となる概念・知識を解説する. セキュリティやネットワークなど,クラウドを利用する上で最低限おさえなければいけないポイントを説明する. ハンズオンでは,はじめての仮想サーバーを AWS に立ち上げる演習を行う.

第二部では,クラウド上で科学計算 (とくに機械学習) を走らせるための入門となる知識・技術を解説する. あわせて, Docker とよばれる仮想計算環境の使用方法を紹介する. 一つ目のハンズオンでは, AWS のクラウドで Jupyter Notebook を起動し簡単な機械学習の計算を走らせる課題を実践する. 二つ目のハンズオンでは,深層学習を用いた自然言語処理により,質問に自動で回答を生成するボットを作成する. 最後に,複数台の GPU インスタンスからなるクラスターを起動し,並列に深層学習のハイパーパラメータサーチを行う方法を紹介する.

第三部では,サーバーレスアーキテクチャとよばれる最新のクラウドのアーキテクチャを紹介する. これは,サーバーの処理能力を負荷に応じてより柔軟に拡大・縮小するための概念であり,それ以前 (Serverful としばしばよばれる) と質的に異なる設計思想をクラウドに導入するものである. ハンズオンでは,サーバーレスクラウドの主要なコンポーネントである Lambda, DynamoDB, S3 の演習を提供する. さらに,サーバーレスの技術を使用して簡単な SNS をクラウド上に作成する.

これらの豊富なハンズオンにより, AWS 上にクラウドシステムを開発するための知識と技術が身につくはずである. いずれのハンズオンも,実用性を重視したものになっており,これらをベースにカスタマイズを施すことで様々な応用が可能である.

本書のフィロソフィー

本書のフィロソフィーを一言で表すなら, "ロケットで宇宙まで飛んでいって一度地球を眺めてみよう!" である.

どういうことか?

ここでいう"地球"とは,クラウドコンピューティングの全体像のことである. 言うまでもなく,クラウドという技術は非常に広範かつ複雑な概念で,幾多の情報技術・ハードウェア・アルゴリズムが精緻に組み合わさってできた総体である. そして,今日では科学研究から日常のインフラ設備に至るまで,我々の社会の多くの部分がクラウド技術によって支えられている.

ここでいう"ロケット"とはこの講義のことである. この講義では,ロケットに乗って宇宙まで飛び立ち,地球(クラウド)の全体を自身の目で眺めてもらう. その際,ロケットの成り立ちや仕組み (背後にある要素技術やプログラムのソースコード) を深くは問わない. 将来,自分が研究などの目的でクラウドを利用することになった際に,改めて学んでもらえば良い. 本書の目的はむしろ,クラウドの最先端に実際に触れ,そこからどんな景色が見えるか(どんな応用が可能か)を実感してもらうことである.

そのような理由で,本書はクラウドの基礎から応用まで幅広いテーマを取り扱う. 第一部はクラウドの基礎から始め,第二部では一気にレベルアップし機械学習(深層学習)をクラウドで実行する手法を解説する. さらに第三部では,サーバーレス・アーキテクチャというここ数年のうちに確立した全く新しいクラウドの設計について解説する. それぞれで本一冊分以上の内容に相当するものであるが,本書はあえてこれらを一冊にまとめ連続的に俯瞰するという野心的な意図をもって執筆された.

決して楽な搭乗体験ではないかもしれないが,このロケットにしがみついてきてもらえれば,とてもエキサイティングな景色が見られることを約束したい.

宇宙からみた地球 (Image from NASA https://www.nasa.gov/image-feature/planet-of-clouds)

AWS アカウント

本書では,ハンズオン形式で AWS のクラウドを実際に動かす演習を提供する. 自分でハンズオンを実行してみたい読者は,各自で AWS のアカウントの作成をしていただく. AWS のアカウントの作成の仕方は巻末付録 ( (#sec:create_aws_account)) に簡単に記載したので,必要に応じて参照していただきたい.

AWS にはいくつかの機能に対して無料利用枠が設定されており,いくつかのハンズオンは無料の範囲内で実行できる. 一方,ほかのハンズオン (とくに機械学習を扱うもの) では数ドル程度のコストが発生する. ハンズオンごとに発生するおおよそのコストについて記述があるので,注意をしながらハンズオンに取り組んでいただきたい.

また,大学などの教育機関における講義で AWS を使用する際は, AWS Educate というプログラムを利用することも可能である. これは,講義の担当者が申請を行うことで,受講する学生に対し AWS クレジットが提供されるというプログラムである. AWS Educate を利用することで金銭的な負担なしに AWS を体験することができる. また,講義を経由せず個人でも AWS Educate に参加することも可能である. AWS Educate からは様々な学習教材が提供されているので,ぜひ活用してもらいたい.

環境構築

本書では, AWS 上にクラウドアプリケーションを展開するハンズオンを実施する. そこで紹介するプログラムを実行するためには,以下の計算機環境が必要である. インストールの方法については,巻末付録 ( (#sec:appendix_settingup)) に記してある. 必要に応じて参照し,環境構築を各自実施していただきたい.

  • UNIX 系コンソール: ハンズオンで紹介するコマンドを実行したり, SSH でサーバーにアクセスするため, UNIX 系のコンソール環境が必要である. Mac または Linux のユーザーは, OS に標準搭載のコンソール(ターミナルとも呼ばれる)を使用すればよい. Windows のユーザーは, Windows Subsystem for Linux (WSL) を使い, Linux の仮想環境のインストールを推奨する ( (#sec:install_wsl) 参照).

  • Docker: 本書では Docker とよばれる仮想計算環境の利用方法を解説する. インストール手順については (#sec:install_docker) を参照のこと.

  • Python: Version 3.6 以上をインストールする. とくに,ハンズオンでは venv モジュールを使用する. venv の使い方は (#venv_quick_guide) 参照のこと.

  • Node.js: version 12.0 以上 をインストールする.

  • AWS CLI: Version 2 をインストールする. インストール手順については (#aws_cli_install) 参照のこと.

  • AWS CDK: Version 1.100 以上をインストールする. Version 2 以降には未対応である. インストール手順については (#aws_cdk_install) 参照のこと.

  • AWS 認証鍵の設定: AWS API をコマンドラインから呼ぶには,認証鍵 (secret key) が設定されている必要がある. 認証鍵の設定については (#aws_cli_install) 参照のこと.

ハンズオン実行用の Docker Image

Python, Node.js, AWS CDK など,ハンズオンのプログラムを実行するために必要なプログラム/ライブラリがインストール済みの Docker image を用意した. また,ハンズオンのソースコードもクローン済みである. Docker の使い方を知っている読者は,これを使えば,諸々のインストールをする必要なく,すぐにハンズオンのプログラムを実行できる.

次のコマンドで起動する.

sh
$ docker run -it tomomano/labc
$ docker run -it tomomano/labc

この Docker image の使い方や詳細は (#sec_handson_docker) に記載している.

前提知識

本書を読むにあたり,要求する前提知識は大学初等程度の計算機科学の知識 (OS,プログラミングなど)のみである. それ以上の前提知識はとくに仮定しない. クラウドの利用経験もゼロで問題ない. が,以下の事前知識があるとよりスムーズに理解をすることができるだろう.

  • Python の基本的な理解: 本書では Python を使ってプログラムの作成を行う. 使用するライブラリは十分抽象化されており,関数の名前を見ただけで意味が明瞭なものがほとんどであるので, Python に詳しくなくても心配する必要はない.

  • Linux コマンドラインの基礎的な理解: クラウドを利用する際,クラウド上に立ち上がるサーバーは基本的に Linux である. Linux のコマンドラインについて知識があると,トラブルシュートなどが容易になる. 筆者のおすすめの参考書は The Linux Command Line by William Shotts である. ウェブで無料で読むことができるので,読んだことのない人はぜひ一読を.

講義に関連する資料

ハンズオンで使うプログラムや教科書のソースコードは以下のウェブページで公開している.

本書で使用するノーテーションなど

  • コードやシェルのコマンドは monospace letter で記述する.

  • シェルに入力するコマンドは,それがシェルコマンドであると明示する目的で,先頭に $ がつけてある. $ はコマンドをコピー&ペーストするときは除かなければならない. 逆に,コマンドの出力には $ はついていない点に留意する.

また,以下のような形式で注意やチップスを提供する.

追加のコメントなどを記す.

発展的な議論やアイディアなどを紹介する.

陥りやすいミスなどの注意事項を述べる.

絶対に犯してはならないミスを指摘する.

]]>
はじめに

本書の目的・内容

本書は,東京大学計数工学科で 2021 年度 S1/S2 タームに開講されている"システム情報工学特論"の講義資料として作成された.

本書の目的は,クラウドの初心者を対象とし,クラウドの基礎的な知識・概念を解説する. また, Amazon Web Services (以下, AWS) の提供するクラウド環境を実例として,具体的なクラウドの利用方法をハンズオンを通して学ぶ.

とくに,科学・エンジニアリングの学生を対象として,研究などの目的でクラウドを利用するための実践的な手順を紹介する. 知識・理論の説明は最小限に留め,実践を行う中で必要な概念の解説を行う予定である. 読者が今後,研究などでクラウドを利用する際の,足がかりとなれば本書の目的は十分達成されたことになる.

本書は以下のような三部構成になっている.

本書の構成
テーマハンズオン

第一部 (1章-4章)

クラウドの基礎

  • AWSに自分のサーバーを立ち上げる

第二部 (5章-9章)

クラウドを活用した機械学習

  • AWS と Jupyter を使って始めるディープラーニング

  • スケーラブルな自動質問回答ボットを作る

  • 並列化されたハイパーパラメータサーチの実装

第三部 (10章-13章)

サーバーレスアーキテクチャ入門

  • Lambda, DynamoDB, S3 の演習

  • 俳句を投稿する SNS "Bashoutter" を作る

第一部は,クラウドの基礎となる概念・知識を解説する. セキュリティやネットワークなど,クラウドを利用する上で最低限おさえなければいけないポイントを説明する. ハンズオンでは,はじめての仮想サーバーを AWS に立ち上げる演習を行う.

第二部では,クラウド上で科学計算 (とくに機械学習) を走らせるための入門となる知識・技術を解説する. あわせて, Docker とよばれる仮想計算環境の使用方法を紹介する. 一つ目のハンズオンでは, AWS のクラウドで Jupyter Notebook を起動し簡単な機械学習の計算を走らせる課題を実践する. 二つ目のハンズオンでは,深層学習を用いた自然言語処理により,質問に自動で回答を生成するボットを作成する. 最後に,複数台の GPU インスタンスからなるクラスターを起動し,並列に深層学習のハイパーパラメータサーチを行う方法を紹介する.

第三部では,サーバーレスアーキテクチャとよばれる最新のクラウドのアーキテクチャを紹介する. これは,サーバーの処理能力を負荷に応じてより柔軟に拡大・縮小するための概念であり,それ以前 (Serverful としばしばよばれる) と質的に異なる設計思想をクラウドに導入するものである. ハンズオンでは,サーバーレスクラウドの主要なコンポーネントである Lambda, DynamoDB, S3 の演習を提供する. さらに,サーバーレスの技術を使用して簡単な SNS をクラウド上に作成する.

これらの豊富なハンズオンにより, AWS 上にクラウドシステムを開発するための知識と技術が身につくはずである. いずれのハンズオンも,実用性を重視したものになっており,これらをベースにカスタマイズを施すことで様々な応用が可能である.

本書のフィロソフィー

本書のフィロソフィーを一言で表すなら, "ロケットで宇宙まで飛んでいって一度地球を眺めてみよう!" である.

どういうことか?

ここでいう"地球"とは,クラウドコンピューティングの全体像のことである. 言うまでもなく,クラウドという技術は非常に広範かつ複雑な概念で,幾多の情報技術・ハードウェア・アルゴリズムが精緻に組み合わさってできた総体である. そして,今日では科学研究から日常のインフラ設備に至るまで,我々の社会の多くの部分がクラウド技術によって支えられている.

ここでいう"ロケット"とはこの講義のことである. この講義では,ロケットに乗って宇宙まで飛び立ち,地球(クラウド)の全体を自身の目で眺めてもらう. その際,ロケットの成り立ちや仕組み (背後にある要素技術やプログラムのソースコード) を深くは問わない. 将来,自分が研究などの目的でクラウドを利用することになった際に,改めて学んでもらえば良い. 本書の目的はむしろ,クラウドの最先端に実際に触れ,そこからどんな景色が見えるか(どんな応用が可能か)を実感してもらうことである.

そのような理由で,本書はクラウドの基礎から応用まで幅広いテーマを取り扱う. 第一部はクラウドの基礎から始め,第二部では一気にレベルアップし機械学習(深層学習)をクラウドで実行する手法を解説する. さらに第三部では,サーバーレス・アーキテクチャというここ数年のうちに確立した全く新しいクラウドの設計について解説する. それぞれで本一冊分以上の内容に相当するものであるが,本書はあえてこれらを一冊にまとめ連続的に俯瞰するという野心的な意図をもって執筆された.

決して楽な搭乗体験ではないかもしれないが,このロケットにしがみついてきてもらえれば,とてもエキサイティングな景色が見られることを約束したい.

宇宙からみた地球 (Image from NASA https://www.nasa.gov/image-feature/planet-of-clouds)

AWS アカウント

本書では,ハンズオン形式で AWS のクラウドを実際に動かす演習を提供する. 自分でハンズオンを実行してみたい読者は,各自で AWS のアカウントの作成をしていただく. AWS のアカウントの作成の仕方は巻末付録 ( (#sec:create_aws_account)) に簡単に記載したので,必要に応じて参照していただきたい.

AWS にはいくつかの機能に対して無料利用枠が設定されており,いくつかのハンズオンは無料の範囲内で実行できる. 一方,ほかのハンズオン (とくに機械学習を扱うもの) では数ドル程度のコストが発生する. ハンズオンごとに発生するおおよそのコストについて記述があるので,注意をしながらハンズオンに取り組んでいただきたい.

また,大学などの教育機関における講義で AWS を使用する際は, AWS Educate というプログラムを利用することも可能である. これは,講義の担当者が申請を行うことで,受講する学生に対し AWS クレジットが提供されるというプログラムである. AWS Educate を利用することで金銭的な負担なしに AWS を体験することができる. また,講義を経由せず個人でも AWS Educate に参加することも可能である. AWS Educate からは様々な学習教材が提供されているので,ぜひ活用してもらいたい.

環境構築

本書では, AWS 上にクラウドアプリケーションを展開するハンズオンを実施する. そこで紹介するプログラムを実行するためには,以下の計算機環境が必要である. インストールの方法については,巻末付録 ( (#sec:appendix_settingup)) に記してある. 必要に応じて参照し,環境構築を各自実施していただきたい.

  • UNIX 系コンソール: ハンズオンで紹介するコマンドを実行したり, SSH でサーバーにアクセスするため, UNIX 系のコンソール環境が必要である. Mac または Linux のユーザーは, OS に標準搭載のコンソール(ターミナルとも呼ばれる)を使用すればよい. Windows のユーザーは, Windows Subsystem for Linux (WSL) を使い, Linux の仮想環境のインストールを推奨する ( (#sec:install_wsl) 参照).

  • Docker: 本書では Docker とよばれる仮想計算環境の利用方法を解説する. インストール手順については (#sec:install_docker) を参照のこと.

  • Python: Version 3.6 以上をインストールする. とくに,ハンズオンでは venv モジュールを使用する. venv の使い方は (#venv_quick_guide) 参照のこと.

  • Node.js: version 12.0 以上 をインストールする.

  • AWS CLI: Version 2 をインストールする. インストール手順については (#aws_cli_install) 参照のこと.

  • AWS CDK: Version 1.100 以上をインストールする. Version 2 以降には未対応である. インストール手順については (#aws_cdk_install) 参照のこと.

  • AWS 認証鍵の設定: AWS API をコマンドラインから呼ぶには,認証鍵 (secret key) が設定されている必要がある. 認証鍵の設定については (#aws_cli_install) 参照のこと.

ハンズオン実行用の Docker Image

Python, Node.js, AWS CDK など,ハンズオンのプログラムを実行するために必要なプログラム/ライブラリがインストール済みの Docker image を用意した. また,ハンズオンのソースコードもクローン済みである. Docker の使い方を知っている読者は,これを使えば,諸々のインストールをする必要なく,すぐにハンズオンのプログラムを実行できる.

次のコマンドで起動する.

sh
$ docker run -it tomomano/labc
$ docker run -it tomomano/labc

この Docker image の使い方や詳細は (#sec_handson_docker) に記載している.

前提知識

本書を読むにあたり,要求する前提知識は大学初等程度の計算機科学の知識 (OS,プログラミングなど)のみである. それ以上の前提知識はとくに仮定しない. クラウドの利用経験もゼロで問題ない. が,以下の事前知識があるとよりスムーズに理解をすることができるだろう.

  • Python の基本的な理解: 本書では Python を使ってプログラムの作成を行う. 使用するライブラリは十分抽象化されており,関数の名前を見ただけで意味が明瞭なものがほとんどであるので, Python に詳しくなくても心配する必要はない.

  • Linux コマンドラインの基礎的な理解: クラウドを利用する際,クラウド上に立ち上がるサーバーは基本的に Linux である. Linux のコマンドラインについて知識があると,トラブルシュートなどが容易になる. 筆者のおすすめの参考書は The Linux Command Line by William Shotts である. ウェブで無料で読むことができるので,読んだことのない人はぜひ一読を.

講義に関連する資料

ハンズオンで使うプログラムや教科書のソースコードは以下のウェブページで公開している.

本書で使用するノーテーションなど

  • コードやシェルのコマンドは monospace letter で記述する.

  • シェルに入力するコマンドは,それがシェルコマンドであると明示する目的で,先頭に $ がつけてある. $ はコマンドをコピー&ペーストするときは除かなければならない. 逆に,コマンドの出力には $ はついていない点に留意する.

また,以下のような形式で注意やチップスを提供する.

追加のコメントなどを記す.

発展的な議論やアイディアなどを紹介する.

陥りやすいミスなどの注意事項を述べる.

絶対に犯してはならないミスを指摘する.

]]>
<![CDATA[ライセンス ]]> https://note.toshiki.dev/development/aws/license https://note.toshiki.dev/development/aws/license Thu, 01 Jul 2021 00:00:00 GMT ライセンス

本教科書およびハンズオンのソースコードは CC BY-NC-ND 4.0 に従うライセンスで公開しています.

教育など非商用の目的での本教科書の使用や再配布は自由に行うことが可能です. 商用目的で本書の全体またはその一部を無断で転載する行為は,これを固く禁じます.

cc_by_nc_nd

]]>
ライセンス

本教科書およびハンズオンのソースコードは CC BY-NC-ND 4.0 に従うライセンスで公開しています.

教育など非商用の目的での本教科書の使用や再配布は自由に行うことが可能です. 商用目的で本書の全体またはその一部を無断で転載する行為は,これを固く禁じます.

cc_by_nc_nd

]]>
<![CDATA[はじめに! ]]> https://note.toshiki.dev/development/aws/main https://note.toshiki.dev/development/aws/main Thu, 01 Jul 2021 00:00:00 GMT はじめに!

本書の目的・内容

本書は,東京大学計数工学科で 2021 年度 S1/S2 タームに開講されている"システム情報工学特論"の講義資料として作成された.

本書の目的は,クラウドの初心者を対象とし,クラウドの基礎的な知識・概念を解説する. また, Amazon Web Services (以下, AWS) の提供するクラウド環境を実例として,具体的なクラウドの利用方法をハンズオンを通して学ぶ.

とくに,科学・エンジニアリングの学生を対象として,研究などの目的でクラウドを利用するための実践的な手順を紹介する. 知識・理論の説明は最小限に留め,実践を行う中で必要な概念の解説を行う予定である. 読者が今後,研究などでクラウドを利用する際の,足がかりとなれば本書の目的は十分達成されたことになる.

本書は以下のような三部構成になっている.

本書の構成
テーマハンズオン

第一部 (1章-4章)

クラウドの基礎

  • AWSに自分のサーバーを立ち上げる

第二部 (5章-9章)

クラウドを活用した機械学習

  • AWS と Jupyter を使って始めるディープラーニング

  • スケーラブルな自動質問回答ボットを作る

  • 並列化されたハイパーパラメータサーチの実装

第三部 (10章-13章)

サーバーレスアーキテクチャ入門

  • Lambda, DynamoDB, S3 の演習

  • 俳句を投稿する SNS "Bashoutter" を作る

第一部は,クラウドの基礎となる概念・知識を解説する. セキュリティやネットワークなど,クラウドを利用する上で最低限おさえなければいけないポイントを説明する. ハンズオンでは,はじめての仮想サーバーを AWS に立ち上げる演習を行う.

第二部では,クラウド上で科学計算 (とくに機械学習) を走らせるための入門となる知識・技術を解説する. あわせて, Docker とよばれる仮想計算環境の使用方法を紹介する. 一つ目のハンズオンでは, AWS のクラウドで Jupyter Notebook を起動し簡単な機械学習の計算を走らせる課題を実践する. 二つ目のハンズオンでは,深層学習を用いた自然言語処理により,質問に自動で回答を生成するボットを作成する. 最後に,複数台の GPU インスタンスからなるクラスターを起動し,並列に深層学習のハイパーパラメータサーチを行う方法を紹介する.

第三部では,サーバーレスアーキテクチャとよばれる最新のクラウドのアーキテクチャを紹介する. これは,サーバーの処理能力を負荷に応じてより柔軟に拡大・縮小するための概念であり,それ以前 (Serverful としばしばよばれる) と質的に異なる設計思想をクラウドに導入するものである. ハンズオンでは,サーバーレスクラウドの主要なコンポーネントである Lambda, DynamoDB, S3 の演習を提供する. さらに,サーバーレスの技術を使用して簡単な SNS をクラウド上に作成する.

これらの豊富なハンズオンにより, AWS 上にクラウドシステムを開発するための知識と技術が身につくはずである. いずれのハンズオンも,実用性を重視したものになっており,これらをベースにカスタマイズを施すことで様々な応用が可能である.

本書のフィロソフィー

本書のフィロソフィーを一言で表すなら, "ロケットで宇宙まで飛んでいって一度地球を眺めてみよう!" である.

どういうことか?

ここでいう"地球"とは,クラウドコンピューティングの全体像のことである. 言うまでもなく,クラウドという技術は非常に広範かつ複雑な概念で,幾多の情報技術・ハードウェア・アルゴリズムが精緻に組み合わさってできた総体である. そして,今日では科学研究から日常のインフラ設備に至るまで,我々の社会の多くの部分がクラウド技術によって支えられている.

ここでいう"ロケット"とはこの講義のことである. この講義では,ロケットに乗って宇宙まで飛び立ち,地球(クラウド)の全体を自身の目で眺めてもらう. その際,ロケットの成り立ちや仕組み (背後にある要素技術やプログラムのソースコード) を深くは問わない. 将来,自分が研究などの目的でクラウドを利用することになった際に,改めて学んでもらえば良い. 本書の目的はむしろ,クラウドの最先端に実際に触れ,そこからどんな景色が見えるか(どんな応用が可能か)を実感してもらうことである.

そのような理由で,本書はクラウドの基礎から応用まで幅広いテーマを取り扱う. 第一部はクラウドの基礎から始め,第二部では一気にレベルアップし機械学習(深層学習)をクラウドで実行する手法を解説する. さらに第三部では,サーバーレス・アーキテクチャというここ数年のうちに確立した全く新しいクラウドの設計について解説する. それぞれで本一冊分以上の内容に相当するものであるが,本書はあえてこれらを一冊にまとめ連続的に俯瞰するという野心的な意図をもって執筆された.

決して楽な搭乗体験ではないかもしれないが,このロケットにしがみついてきてもらえれば,とてもエキサイティングな景色が見られることを約束したい.

宇宙からみた地球 (Image from NASA https://www.nasa.gov/image-feature/planet-of-clouds)

AWS アカウント

本書では,ハンズオン形式で AWS のクラウドを実際に動かす演習を提供する. 自分でハンズオンを実行してみたい読者は,各自で AWS のアカウントの作成をしていただく. AWS のアカウントの作成の仕方は巻末付録 (AWS アカウントの取得) に簡単に記載したので,必要に応じて参照していただきたい.

AWS にはいくつかの機能に対して無料利用枠が設定されており,いくつかのハンズオンは無料の範囲内で実行できる. 一方,ほかのハンズオン (とくに機械学習を扱うもの) では数ドル程度のコストが発生する. ハンズオンごとに発生するおおよそのコストについて記述があるので,注意をしながらハンズオンに取り組んでいただきたい.

また,大学などの教育機関における講義で AWS を使用する際は, AWS Educate というプログラムを利用することも可能である. これは,講義の担当者が申請を行うことで,受講する学生に対し AWS クレジットが提供されるというプログラムである. AWS Educate を利用することで金銭的な負担なしに AWS を体験することができる. また,講義を経由せず個人でも AWS Educate に参加することも可能である. AWS Educate からは様々な学習教材が提供されているので,ぜひ活用してもらいたい.

環境構築

本書では, AWS 上にクラウドアプリケーションを展開するハンズオンを実施する. そこで紹介するプログラムを実行するためには,以下の計算機環境が必要である. インストールの方法については,巻末付録 (Appendix: 環境構築) に記してある. 必要に応じて参照し,環境構築を各自実施していただきたい.

  • UNIX 系コンソール: ハンズオンで紹介するコマンドを実行したり, SSH でサーバーにアクセスするため, UNIX 系のコンソール環境が必要である. Mac または Linux のユーザーは, OS に標準搭載のコンソール(ターミナルとも呼ばれる)を使用すればよい. Windows のユーザーは, Windows Subsystem for Linux (WSL) を使い, Linux の仮想環境のインストールを推奨する (WSL のインストール 参照).

  • Docker: 本書では Docker とよばれる仮想計算環境の利用方法を解説する. インストール手順については Docker のインストール を参照のこと.

  • Python: Version 3.6 以上をインストールする. とくに,ハンズオンでは venv モジュールを使用する. venv の使い方は Python クイックガイド 参照のこと.

  • Node.js: version 12.0 以上 をインストールする.

  • AWS CLI: Version 2 をインストールする. インストール手順については AWS CLI のインストール 参照のこと.

  • AWS CDK: Version 1.100 以上をインストールする. Version 2 以降には未対応である. インストール手順については AWS CDK のインストール 参照のこと.

  • AWS 認証鍵の設定: AWS API をコマンドラインから呼ぶには,認証鍵 (secret key) が設定されている必要がある. 認証鍵の設定については AWS CLI のインストール 参照のこと.

ハンズオン実行用の Docker Image

Python, Node.js, AWS CDK など,ハンズオンのプログラムを実行するために必要なプログラム/ライブラリがインストール済みの Docker image を用意した. また,ハンズオンのソースコードもクローン済みである. Docker の使い方を知っている読者は,これを使えば,諸々のインストールをする必要なく,すぐにハンズオンのプログラムを実行できる.

次のコマンドで起動する.

sh
$ docker run -it tomomano/labc
$ docker run -it tomomano/labc

この Docker image の使い方や詳細は ハンズオン実行用の Docker image の使い方 に記載している.

前提知識

本書を読むにあたり,要求する前提知識は大学初等程度の計算機科学の知識 (OS,プログラミングなど)のみである. それ以上の前提知識はとくに仮定しない. クラウドの利用経験もゼロで問題ない. が,以下の事前知識があるとよりスムーズに理解をすることができるだろう.

  • Python の基本的な理解: 本書では Python を使ってプログラムの作成を行う. 使用するライブラリは十分抽象化されており,関数の名前を見ただけで意味が明瞭なものがほとんどであるので, Python に詳しくなくても心配する必要はない.

  • Linux コマンドラインの基礎的な理解: クラウドを利用する際,クラウド上に立ち上がるサーバーは基本的に Linux である. Linux のコマンドラインについて知識があると,トラブルシュートなどが容易になる. 筆者のおすすめの参考書は The Linux Command Line by William Shotts である. ウェブで無料で読むことができるので,読んだことのない人はぜひ一読を.

講義に関連する資料

ハンズオンで使うプログラムや教科書のソースコードは以下のウェブページで公開している.

https://github.com/tomomano/learn-aws-by-coding

本書で使用するノーテーションなど

  • コードやシェルのコマンドは monospace letter で記述する.

  • シェルに入力するコマンドは,それがシェルコマンドであると明示する目的で,先頭に $ がつけてある. $ はコマンドをコピー&ペーストするときは除かなければならない. 逆に,コマンドの出力には $ はついていない点に留意する.

また,以下のような形式で注意やチップスを提供する.

追加のコメントなどを記す.

発展的な議論やアイディアなどを紹介する.

陥りやすいミスなどの注意事項を述べる.

絶対に犯してはならないミスを指摘する.

クラウド概論

クラウドとは?

Cloud

クラウドとはなにか? クラウドという言葉は,それ自身がとても広い意味をもつので,厳密な定義付けを行うことは難しい.

学術的な意味でのクラウドの定義づけをするとしたら,NIST(米国・国立標準技術研究所) による The NIST Definition of Cloud Computing が引用されることが多い. ここに記載されたクラウドの定義・モデルを図示したのが figure_title である.

The NIST Definition of Cloud Computing

これによると,クラウドとは以下の要件が満たされたハードウェア/ソフトウェアの総体のことをいう.

  • On-demand self-service 利用者のリクエストに応じて計算資源が自動的に割り当てられる.

  • Broad network access 利用者はネットワークを通じてクラウドにアクセスできる.

  • Resource pooling クラウドプロバイダーは,所有する計算資源を分割することで複数の利用者に計算資源を割り当てる.

  • Rapid elasticity 利用者のリクエストに応じて,迅速に計算資源の拡大あるいは縮小を行うことができる.

  • Measured service 計算資源の利用量を計測・監視することができる.

…と,いわれても抽象的でよくわからないかもしれない.もう少し具体的な話をする.

個人が所有する計算機で, CPU をアップグレードしようと思ったら,物理的に筐体を開け,CPU ソケットを露出させ,新しい CPU に交換する必要があるだろう. あるいは,ストレージがいっぱいになってしまったら,古いディスクを抜き取り,新しいディスクを挿入する必要がある. 計算機の場所を移動させたときには,新しい部屋の LAN ケーブルを差し込まないとネットワークには接続できない.

クラウドでは,これらの操作がプログラムからのコマンドによって実行できる. CPU が 1000 個欲しいと思ったならば,そのようにクラウドプロバイダーにリクエストを送れば良い. すると,数分もしないうちに 1000 CPU の計算資源が割り当てられる. ストレージを 1TB から 10TB に拡張しようと思ったならば,そのようにコマンドを送ればよい (これは,Google Drive や Dropbox などのサービスなどで馴染みのある人も多いだろう). 計算資源を使い終わったら,そのことをプロバイダーに伝えれば,割り当て分はすぐさま削除される. クラウドプロバイダーは,使った計算資源の量を正確にモニタリングしており,その量をもとに利用料金の計算が行われる.

このように,クラウドの本質は物理的なハードウェアの仮想化・抽象化であり,利用者はコマンドを通じて,まるでソフトウェアの一部かのように,物理的なハードウェアの管理・運用を行うことができる. もちろん,背後では,データセンターに置かれた膨大な数の計算機が大量の電力を消費しながら稼働している. クラウドプロバイダーはデータセンターの計算資源を上手にやりくりし,ソフトウェアとしてのインターフェースをユーザーに提供することで,このような仮想化・抽象化を達成しているわけである. クラウドプロバイダーの視点からすると,大勢のユーザーに計算機を貸し出し,データセンターの稼働率を常時 100%に近づけることで,利益率の最大化を図っているのである.

著者の言葉で,クラウドの重要な特性を定義するならば,以下のようになる.

クラウドとは計算機ハードウェアの抽象化である.つまり,物理的なハードウェアをソフトウェアの一部かのように自在に操作・拡大・接続することを可能にする技術である.

先述の The NIST Definition of Cloud Computing に戻ると,クラウドプロバイダーによるクラウドサービスの形態としては,次の三つが定義されている (figure_title).

  • Software as a Service (SaaS): クラウド上で実行されるアプリケーションをサービスとして利用者に提供する形態. 例として, Google Drive や Slack などが挙げられる. 利用者は,背後にあるクラウドのインフラ (ネットワークやサーバーなど) には直接触れず,アプリケーションとして提供されているクラウドサービスを享受する.

  • Platform as a Service (PaaS): 顧客の作成したアプリケーション (多くの場合データベースと API リクエスト処理を行うサーバーのコードから構成される) をデプロイする環境をサービスとして利用者に提供する形態. PaaS では利用者はクラウドのインフラに直接触れることはなく,計算負荷が増減した際のサーバーのスケーリングはクラウドプロバイダーによってなされる. 例としては, Google App Engine や Heroku などがある.

  • Infrastructure as a Service (IaaS): クラウド上の計算インフラストラクチャーを従量課金制で利用者に提供する形態. 利用者は必要なネットワーク・サーバー・ストレージをプロバイダーから借り受け,そこに自身のアプリケーションを展開し運用する. IaaS の例としては AWS EC2 などが挙げられる.

本書が扱うのは,主に IaaS におけるクラウド開発である. すなわち,開発者がクラウドのインフラを直接操作し,所望のネットワーク・サーバー・ストレージなどを一から構成し,そこにアプリケーションを展開するというクラウド開発である. この意味において,クラウドの開発とはクラウドインフラストラクチャーを定義・展開するプログラムを構築するステップインフラ上で実際に走るアプリケーションを作成するステップの二つに分けることができる. この二つは,プログラマーの技術としてはある程度分業を行うことが可能であるが,最も効率化・最適化されたクラウドシステムを構築するためには両方の理解が必須である. 本書では,前者 (クラウドインフラの記述) に重きを置きつつ,アプリケーションレイヤーの話題も取り扱う. PaaS とは,開発者はアプリケーションレイヤーの開発に注力し,クラウドインフラの部分はクラウドプロバイダーに依存するという概念である. PaaS は,クラウドインフラの開発が不要になることで開発の時間が短縮されるが,細かなインフラの挙動はコントロールできないという限界がある. 本書では PaaS についてはとくに取り扱わない.

SaaS は本書の文脈では開発による"成果物"と捉えられるだろう. すなわち, IaaS を構成するプログラムを作成し展開することによって,一般の人が利用できるようなウェブ上の計算サービスやデータベースを提供することが開発の最終ゴールである. 本書のハンズオンではその実例として,シンプルな SNS の作成 (Hands-on #6: Bashoutter) などの演習を提供する.

なお,最近では Function as a Service (FaaS) やサーバーレスコンピューティングなども新たなクラウドのカテゴリとして認知されている. これらの概念については Hands-on #5: サーバーレス入門 などの章で詳しく触れていく. 本書を読み進める中で明らかになるように,クラウドの技術は日進月歩である. 本書では実用的・教育的な観点から,従来的なクラウドの設計概念に触れたあと,サーバーレスなどの最新の技術も網羅するので,楽しみにしながら読み進めていただきたい.

最後に,The NIST Definition of Cloud Computing によると,クラウドの運用形態について次のような定義がなされている (figure_title). 特定の組織・団体・企業の内部のみで使用されるクラウドを,プライベートクラウド (private cloud) とよぶ. 例えば,大学や研究機関では,その機関の構成員向けの大規模計算機サーバーが運用されていることが多い. プライベートクラウドは,組織の構成員ならば無料もしくは極めて割安のコストで計算を実行できる. しかし,使用できる計算資源の上限は限られる場合が多く,拡張時の柔軟性に欠ける場合もある.

一方,商用のサービスとして一般の顧客に向けたクラウドのことを,パブリッククラウド (public cloud) とよぶ. 有名なパブリッククラウドプラットフォームの例を挙げると, Google 社が提供する Google Cloud Platform (GCP), Microsoft 社が提供する Azure, Amazon 社が提供する Amazon Web Services (AWS) などがある. パブリッククラウドを利用する場合は,プロバイダーの設定した利用料金を支払うことになる. その分,巨大なデータセンターを運用する企業の計算資源にアクセスすることができるので,計算のキャパシティは無尽蔵にあるといって過言でない.

第三のクラウドの運用形態として,コミュニティクラウド (community cloud) が挙げられる. これは,例えば政府の省庁・機関など目的・役割を共有する団体・組織が共有して運用するクラウドを指す. 最後に,ハイブリッドクラウド (hybrid cloud) という形態もあり,これはプライベート・パブリック・コミュニティクラウドの二つ以上の組み合わせによって構成されるクラウドのことである. データ保護の観点から,いくつかの機密データやプライバシーに関わる情報はプライベートクラウドに保持し,残りのシステムをパブリッククラウドに依存する,などの形態が想定される.

本書で説明するのは,基本的にパブリッククラウドを使ったクラウド開発である. 特に,Amazon Web Services (AWS) を使用して,具体的な技術と概念を学んでいく. 一方で,サーバーのスケーリングや仮想計算環境などのテクニックはすべてのクラウドに共通な概念であるので,クラウドのプラットフォームが変わろうと一般に通用する知識も同時に身につくはずだ.

なぜクラウドを使うのか?

上述のように,クラウドとはプログラムを通じて自由に計算資源を操作することのできる計算環境である. ここでは,リアルなローカル計算環境と比べて,なぜクラウドを使うと良いことがあるのかについて述べたい.

  1. 自由にサーバーのサイズをスケールできる

    なにか新しいプロジェクトを始めるとき,あらかじめ必要なサーバーのスペックを知るのは難しい. いきなり大きなサーバーを買うのはリスクが高い. 一方で,小さすぎるサーバーでは,後のアップグレードが面倒である. クラウドを利用すれば,プロジェクトを進めながら,必要な分だけの計算資源を確保することができる. 2. 自分でサーバーをメンテナンスする必要がない

    悲しいことに,コンピュータとは古くなるものである.最近の技術の進歩の速度からすると,5 年も経てば,もはや当時の最新コンピュータも化石と同じである. 5 年ごとにサーバーを入れ替えるのは相当な手間である. またサーバーの停電や故障など不意の障害への対応も必要である. クラウドでは,そのようなインフラの整備やメンテナンスはプロバイダーが自動でやってくれるので,ユーザーが心配する必要がない. 3. 初期コスト 0

    自前の計算環境とクラウドの,経済的なコストのイメージを示したのが figure_title である. クラウドを利用する場合の初期コストは基本的に 0 である. その後,使った利用量に応じてコストが増大していく. 一方,自前の計算環境では,大きな初期コストが生じる. その分,初期投資後のコストの増加は,電気利用料やサーバー維持費などに留まるため,クラウドを利用した場合よりも傾きは小さくなる. 自前の計算機では,ある一定期間後,サーバーのアップグレードなどによる支出が生じることがある. 一方,クラウドを利用する場合は,そのような非連続なコストの増大は基本的に生じない. クラウドのコストのカーブが,自前計算環境のコストのカーブの下にある範囲においては,クラウドを使うことは経済的なコスト削減につながる.

    クラウドと自前計算機環境の経済的コストの比較

とくに,**1.**の点は研究の場面では重要であると筆者は感じる. 研究をやっていて,四六時中計算を走らせ続けるという場合は少ない. むしろ,新しいアルゴリズムが完成したとき・新しいデータが届いたとき,集中的・突発的に計算タスクが増大することが多いだろう. そういったときに,フレキシブルに計算力を増強させることができるのは,クラウドを使う大きなメリットである.

ここまでクラウドを使うメリットを述べたが,逆に,デメリットというのも当然存在する.

  1. クラウドは賢く使わないといけない

    figure_title で示したコストのカーブにあるとおり,使い方によっては自前の計算環境のほうがコスト的に有利な場面は存在しうる. クラウドを利用する際は,使い終わった計算資源はすぐに削除するなど,利用者が賢く管理を行う必要があり,これを怠ると思いもしない額の請求が届く可能性がある. 2. セキュリティ

    クラウドは,インターネットを通じて世界のどこからでもアクセスできる状態にあり,セキュリティ管理を怠ると簡単にハッキングの対象となりうる. ハッキングを受けると,情報流出だけでなく,経済的な損失を被る可能性がある. 3. ラーニングカーブ

    上記のように,コスト・セキュリティなど,クラウドを利用する際に留意しなければならない点は多い. 賢くクラウドを使うには,十分なクラウドの理解が必要であり,そのラーニングカーブを乗り越える必要がある.

Mac/Linux などでコマンドを入力するときに使用する,あの黒い画面のことを Terminal とよんだりする. この言葉の語源をご存知だろうか?

Terminal

この言葉の語源は,コンピュータが誕生して間もない頃の時代に遡る. その頃のコンピュータというと,何千何万のという数の真空管が接続された,会議室一個分くらいのサイズのマシンであった. そのような高価でメンテが大変な機材であるから,当然みんなでシェアして使うことが前提となる. ユーザーがコンピュータにアクセスするため,マシンからは何本かのケーブルが伸び,それぞれにキーボードとスクリーンが接続されていた… これを Terminal とよんでいたのである. 人々は,代わる代わる Terminal の前に座って,計算機との対話を行っていた.

時代は流れ,Windows や Mac などのいわゆるパーソナルコンピュータの出現により,コンピュータはみんなで共有するものではなく,個人が所有するものになった.

最近のクラウドの台頭は,みんなで大きなコンピュータをシェアするという,最初のコンピュータの使われ方に原点回帰していると捉えることもできる. 一方で,スマートフォンやウェアラブルなどのエッジデバイスの普及も盛んであり,個人が複数の"小さな"コンピュータを所有する,という流れも同時に進行しているのである.

AWS 入門

AWS とは?

本書では,クラウドの実践を行うプラットフォームとして, AWS を用いる. 実践にあたって,最低限必要な AWS の知識を本章では解説しよう.

AWS (Amazon Web Services) は Amazon 社が提供する総合的なクラウドプラットフォームである. AWS は Amazon 社が持つ膨大な計算リソースを貸し出すクラウドサービスとして,2006 年に誕生した. 2021 年では,クラウドプロバイダーとして最大のマーケットシェア (約 32%) を保持している (参照). Netflix や Slack をはじめとした多くのウェブ関連のサービスで,一部または全てのサーバーリソースが AWS から提供されているとのことである. よって,知らないうちに AWS の恩恵にあずかっている人も少なくないはずだ.

最大のシェアをもつだけに,機能・サービスの幅広さはほかのクラウドプラットフォームと比べ抜きんでている. また,利用者数が多いことを反映して,公式あるいはサードパーティによる技術紹介記事が数多くウェブ上に存在しているだけでなく,ライブラリのユーザーコミュニティも大きく問題解決が捗るのも魅力の一つだ. 初期のころウェブビジネスを行う企業がユーザーの大半を占めていたが,最近は大学などでの科学研究用途としても頻繁に用いられるようになってきている.

AWS の機能・サービス

figure_title は,執筆時点において AWS で提供されている主要な機能・サービスの一覧である.

AWSで提供されている主要なサービス一覧

計算,ストレージ,データベース,ネットワーク,セキュリティなど,クラウドの構築に必要な様々な要素が独立したコンポーネントとして提供されている. 基本的に,これらを組み合わせることで一つのクラウドシステムができあがる.

また,機械学習・音声認識・AR/VR など,特定のアプリケーションにパッケージ済みのサービスも提供されている. これらを合計すると全部で 170 個以上のサービスが提供されているとのことである (参照).

AWS の初心者が陥りがちなのは,大量のサービスの数に圧倒され,どこから手をつけたらよいのかわからなくなる,という状況である. たくさんのサービスの中から,どのサービスをどの順番で学んでいったらいいのか,その道筋すら明らかでなく,大きな参入障壁となっていることは間違いない. だが実のところ, AWS の基本的な構成要素はそのうちの数個のみに限られる. 基本要素となる機能の使い方を知れば, AWS のおおよそのリソースを使いこなすことが可能になる. ほかの機能の多くは,基本の要素を組み合わせて特定のアプリケーションに特化したパッケージとして AWS が用意したものである. そのポイントを認知することが, AWS の学習の最初のステップである.

ここでは, AWS 上でクラウドシステムを構築するときの基本となる構成要素を列挙する. これらは後のハンズオンで実際にプログラムを書きながら体験する. 現時点では,名前だけでも頭の片隅に記憶してもらえればよい.

計算

S3 EC2 (Elastic Compute Cloud) 様々なスペックの仮想マシンを作成し,計算を実行することができる. クラウドの最も基本となる構成要素である. Hands-on #1: 初めての EC2 インスタンスを起動する, Hands-on #2: AWS でディープラーニングを実践, Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する で詳しく触れる.

S3 Lambda Function as a Service (FaaS) とよばれる,小さな計算をサーバーなしで実行するためのサービス. サーバーレスアーキテクチャの章 (Serverless architecture) で詳しく解説する.

ストレージ

S3 EBS (Elastic Block Store) EC2 に付与することのできる仮想データドライブ. いわゆる"普通の"(一般的な OS で使われている)ファイルシステムを思い浮かべてくれたらよい.

S3 S3 (Simple Storage Service) Object Storage とよばれる,API を使ってデータの読み書きを行う,いうなれば”クラウド・ネイティブ”なデータの格納システムである. サーバーレスアーキテクチャの章 (Serverless architecture) で詳しく解説する.

データベース

S3 DynamoDB NoSQL 型のデータベースサービス (知っている人は mongoDB などを思い浮かべたらよい). サーバーレスアーキテクチャの章 (Serverless architecture) で詳しく解説する.

ネットワーク

S3 VPC(Virtual Private Cloud) AWS 上に仮想ネットワーク環境を作成し,仮想サーバー間の接続を定義したり,外部からのアクセスなどを管理する. EC2 は VPC の内部に配置されなければならない.

API Gateway S3 API のエンドポイントとバックエンドのサービス (Lambda など) を接続する際に用いる,リバースプロキシとしての役割を担う. Hands-on #6: Bashoutter で詳しく解説する.

Region と Availability Zone

AWS を使用する際に知っておかなければならない重要な概念として, リージョン (Region)Availability Zone (AZ) がある (figure_title). 以下ではこの概念について簡単に記述する.

AWSにおける Region と Availability Zones

リージョン (Region) とは,おおまかに言うとデータセンターの所在地のことである. 執筆時点において, AWS は世界の 25 の国と地域でデータセンターを所有している. figure_title は執筆時点で利用できるリージョンの世界地図を示している. 日本では東京と大阪にデータセンターがある. 各リージョンには固有の ID がついており,例えば東京は ap-northeast-1, 米国オハイオ州は us-east-2,などと定義されている.

Regions in AWS(出典: https://aws.amazon.com/about-aws/global-infrastructure/)

AWS コンソールにログインすると,画面右上のメニューバーでリージョンを選択することができる(figure_title, 赤丸で囲った箇所). EC2, S3 などの AWS のリソースは,リージョンごとに完全に独立である. したがって,リソースを新たにデプロイする際,あるいはデプロイ済みのリソースを閲覧する際は,コンソールのリージョンが正しく設定されているか,確認する必要がある. ウェブビジネスを展開する場合などは,世界の各地にクラウドを展開する必要があるが,個人的な研究用途として用いる場合は,最寄りのリージョン (i.e. 東京) を使えば基本的に問題ない.

AWSコンソールでリージョンを選択

Avaialibity Zone (AZ) とは,リージョン内で地理的に隔離されたデータセンターのことである. それぞれのリージョンは 2 個以上の AZ を有しており,もし一つの AZ で火災や停電などが起きた場合でも,ほかの AZ がその障害をカバーすることができる. また, AZ 間は高速な AWS 専用ネットワーク回線で結ばれているため, AZ 間のデータ転送は極めて早い. AZ は,ビジネスなどでサーバーダウンが許容されない場合などに注意すべき概念であり,個人的な用途で使う限りにおいてはあまり深く考慮する必要はない.言葉の意味だけ知っておけば十分である.

AWS を使用する際,どこのリージョンを指定するのがよいのだろうか? インターネットの接続速度の観点からは,地理的に一番近いリージョンを使用するのが一般的によいだろう. 一方, EC2 の利用料などはリージョンごとに価格設定が若干 (10-20%程度) 異なる. したがって,自分が最も頻繁に利用するサービスの価格が最も安く設定されているリージョンを選択する,というのも重要な視点である. また,いくつかのサービスは,特定のリージョンで利用できない場合もある. これらのポイントから総合的に判断して使用するリージョンを決めると良い.

AWS Educate を利用している読者へ

執筆時点において,AWS Educate による Starter Account を使用している場合は us-east-1 region のみ利用できる (参照).

AWS でのクラウド開発

AWS のクラウドの全体像がわかってきたところで,次のトピックとして,どのようにして AWS 上にクラウドの開発を行い,展開していくかについての概略を解説しよう.

AWS のリソースを追加・編集・削除するなどの操作を実行するには,コンソールを用いる方法と,API を用いる方法の,二つの経路がある.

コンソール画面からリソースを操作する

AWS のアカウントにログインすると,まず最初に表示されるのがAWS コンソールである (figure_title).

AWSマネージメントコンソール画面

コンソールを使うことで, EC2 のインスタンスを立ち上げたり,S3 のデータを追加・削除したり,ログを閲覧したりなど,AWS 上のあらゆるリソースの操作を GUI (Graphical User Interface) を通して実行することができる. 初めて触る機能をポチポチと試したり,デバッグを行うときなどにとても便利である

コンソールはさらっと機能を試したり,開発中のクラウドのデバッグをするときには便利なのであるが,実際にクラウドの開発をする場面でこれを直接いじることはあまりない. むしろ,次に紹介する API を使用して,プログラムとしてクラウドのリソースを記述することで開発を行うのが一般的である. そのような理由で,本書では AWS コンソールを使った AWS の使い方はあまり触れない. AWS のドキュメンテーションには,たくさんの チュートリアル が用意されており,コンソール画面から様々な操作を行う方法が記述されているので,興味がある読者はそちらを参照されたい.

API からリソースを操作する

API (Application Programming Interface) を使うことで,コマンドを AWS に送信し,クラウドのリソースの操作をすることができる. API とは,端的に言えば AWS が公開しているコマンドの一覧であり,GET, POST, DELETE などの REST API から構成されている (REST API については REST API で簡単に解説する). が,直接 REST API を入力するのは面倒であるので,その手間を解消するための様々なツールが提供されている.

例えば, AWS CLI は, UNIX コンソールから AWS API を実行するための CLI (Command Line Interface) である. CLI に加えて,いろいろなプログラミング言語での SDK (Software Development Kit) が提供されている.以下に一例を挙げる.

具体的な API の使用例を見てみよう.

S3 に新しい保存領域 (Bucket (バケット) とよばれる) を追加したいとしよう. AWS CLI を使った場合は,次のようなコマンドを打てばよい.

sh
$ aws s3 mb s3://my-bucket --region ap-northeast-1
$ aws s3 mb s3://my-bucket --region ap-northeast-1

上記のコマンドは, my-bucket という名前のバケットを, ap-northeast-1 のリージョンに作成する.

Python からこれと同じ操作を実行するには, boto3 ライブラリを使って,次のようなスクリプトを実行する.

python
import boto3

s3_client = boto3.client("s3", region_name="ap-northeast-1")
s3_client.create_bucket(Bucket="my-bucket")
import boto3

s3_client = boto3.client("s3", region_name="ap-northeast-1")
s3_client.create_bucket(Bucket="my-bucket")

もう一つ例をあげよう.

新しい EC2 のインスタンス(インスタンスとは,起動状態にある仮想サーバーの意味である)を起動するには,次のようなコマンドを打てば良い.

sh
$ aws ec2 run-instances --image-id ami-xxxxxxxx --count 1 --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-903004f8 --subnet-id subnet-6e7f829e
$ aws ec2 run-instances --image-id ami-xxxxxxxx --count 1 --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-903004f8 --subnet-id subnet-6e7f829e

このコマンドにより, t2.micro というタイプ (1 vCPU, 1.0 GB RAM) のインスタンスが起動する. ここではその他のパラメータの詳細の説明は省略する (ハンズオン (Hands-on #1: 初めての EC2 インスタンスを起動する) で詳しく解説する).

Python から上記と同じ操作を実行するには,以下のようなスクリプトを使う.

python
import boto3

ec2_client = boto3.client("ec2")
ec2_client.run_instances(
    ImageId="ami-xxxxxxxxx",
    MinCount=1,
    MaxCount=1,
    KeyName="MyKeyPair",
    InstanceType="t2.micro",
    SecurityGroupIds=["sg-903004f8"],
    SubnetId="subnet-6e7f829e",
)
import boto3

ec2_client = boto3.client("ec2")
ec2_client.run_instances(
    ImageId="ami-xxxxxxxxx",
    MinCount=1,
    MaxCount=1,
    KeyName="MyKeyPair",
    InstanceType="t2.micro",
    SecurityGroupIds=["sg-903004f8"],
    SubnetId="subnet-6e7f829e",
)

以上の例を通じて,API によるクラウドのリソースの操作のイメージがつかめてきただろうか? コマンド一つで,新しい仮想サーバーを起動したり,データの保存領域を追加したり,任意の操作を実行できるわけである. 基本的に,このようなコマンドを複数組み合わせていくことで,自分の望む CPU・RAM・ネットワーク・ストレージが備わった計算環境を構築することができる. もちろん,逆の操作 (リソースの削除) も API を使って実行できる.

ミニ・ハンズオン: AWS CLI を使ってみよう

ここでは,ミニ・ハンズオンとして,AWS CLI を実際に使ってみる. AWS CLI は先述のとおり, AWS 上の任意のリソースの操作が可能であるが,ここでは一番シンプルな,S3 を使ったファイルの読み書きを実践する (EC2 の操作は少し複雑なので,第一回ハンズオンで行う). aws s3 コマンドの詳しい使い方は 公式ドキュメンテーションを参照.

AWS CLI のインストールについては, AWS CLI のインストール を参照.

以下に紹介するハンズオンは,基本的に S3 の無料枠 の範囲内で実行することができる.

以下のコマンドを実行する前に,AWS の認証情報が正しく設定されていることを確認する. これには ~/.aws/credentials のファイルに設定が書き込まれているか,環境変数 (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION) が定義されている必要がある. 詳しくは AWS CLI のインストール を参照.

まずは,S3 にデータの格納領域 (Bucket とよばれる.一般的な OS での"ドライブ"に相当する) を作成するところから始めよう.

sh
$ bucketName="mybucket-$(openssl rand -hex 12)"
$ echo $bucketName
$ aws s3 mb "s3://${bucketName}"
$ bucketName="mybucket-$(openssl rand -hex 12)"
$ echo $bucketName
$ aws s3 mb "s3://${bucketName}"

S3 のバケットの名前は, AWS 全体で一意的でなければならないことから,前述のコマンドではランダムな文字列を含んだバケットの名前を生成し,bucketName という変数に格納している. そして, aws s3 mb (mb は make bucket の略) によって,新しいバケットを作成する.

次に,バケットの一覧を取得してみよう.

sh
$ aws s3 ls

2020-06-07 23:45:44 mybucket-c6f93855550a72b5b66f5efe
$ aws s3 ls

2020-06-07 23:45:44 mybucket-c6f93855550a72b5b66f5efe

先ほど作成したバケットがリストにあることを確認できる.

本書のノーテーションとして,コマンドラインに入力するコマンドは,それがコマンドであると明示する目的で先頭に $ がつけてある. $ はコマンドをコピー&ペーストするときは除かなければならない. 逆に,コマンドの出力は $ なしで表示されている.

次に,バケットにファイルをアップロードする.

sh
$ echo "Hello world" > hello_world.txt
$ aws s3 cp hello_world.txt "s3://${bucketName}/hello_world.txt"
$ echo "Hello world" > hello_world.txt
$ aws s3 cp hello_world.txt "s3://${bucketName}/hello_world.txt"

上では hello_world.txt というダミーのファイルを作成して,それをアップロードした.

それでは,バケットの中にあるファイルの一覧を取得してみる.

sh
$ aws s3 ls "s3://${bucketName}" --human-readable

2020-06-07 23:54:19   13 Bytes hello_world.txt
$ aws s3 ls "s3://${bucketName}" --human-readable

2020-06-07 23:54:19   13 Bytes hello_world.txt

先ほどアップロードしたファイルがたしかに存在することがわかる.

最後に,使い終わったバケットを削除する.

sh
$ aws s3 rb "s3://${bucketName}" --force
$ aws s3 rb "s3://${bucketName}" --force

rb は remove bucket の略である. デフォルトでは,バケットの中にファイルが存在すると削除できない. 空でないバケットを強制的に削除するには --force のオプションを付ける.

以上のように,AWS CLI を使って S3 バケットに対しての一連の操作を実行できた. EC2 や Lambda, DynamoDB などについても同様に AWS CLI を使ってあらゆる操作を実行できる.

Amazon Resource Name (ARN)

AWS 上のあらゆるリソースには, Amazon Resource Name (ARN) という固有の ID が付与されている. ARN は arn:aws:s3:::my_bucket/ のようなフォーマットで記述され,ARN を使用することで,特定の AWS リソース (S3 のバケットや EC2 のインスタンス) を一意的に参照することができる.

S3 バケットや EC2 インスタンスなどには ARN に加えて,人間が読みやすい名前を定義することも可能である. この場合は,ARN または名前のどちらを用いても同じリソースを参照することが可能である.

CloudFormation と AWS CDK

CloudFormation による Infrastructure as Code (IaC)

前節で述べたように,AWS API を使うことでクラウドのあらゆるリソースの作成・管理が可能である. よって,原理上は, API のコマンドを組み合わせていくことで,自分の作りたいクラウドを設計することができる.

しかし,ここで実用上考慮しなければならない点が一つある. AWS API には大きく分けて,リソースを操作するコマンドと,タスクを実行するコマンドがあることである (figure_title).

AWS APIはリソースを操作するコマンドとタスクを実行するコマンドに大きく分けられる.リソースを記述・管理するのに使われるのが, CloudFormation と CDK である.

リソースを操作するとは,EC2 のインスタンスを起動したり,S3 のバケットを作成したり,データベースに新たなテーブルを追加する,などの静的なリソースを準備する 操作を指す. "ハコ"を作る操作とよんでも良いだろう. このようなコマンドは,クラウドのデプロイ時にのみ,一度だけ実行されればよい

タスクを実行するコマンド とは, EC2 のインスタンスにジョブを投入したり, S3 のバケットにデータを読み書きするなどの操作を指す. これは, EC2 や S3 などのリソース ("ハコ") を前提として,その内部で実行されるべき計算を記述するものである. 前者に比べてこちらは動的な操作を担当する,と捉えることもできる.

そのような観点から,インフラを記述するプログラムタスクを実行するプログラムはある程度分けて管理されるべきである. クラウドの開発は,クラウドの(静的な)リソースを記述するプログラムを作成するステップと,インフラ上で動く動的な操作を行うプログラムを作成するステップの二段階に分けて考えることができる.

AWS での静的リソースを管理するための仕組みが, CloudFormation である. CloudFormation とは, CloudFormation の文法に従ったテキストファイルを使って,AWS のインフラを記述する仕組みである. CloudFormation を使って,たとえば,EC2 のインスタンスをどれくらいのスペックで,何個起動するか,インスタンス間はどのようなネットワークで結び,どのようなアクセス権限を付与するか,などのリソースの要件を逐次的に記述することができる. 一度 CloudFormation ファイルができ上がれば,それにしたがったクラウドシステムをコマンド一つで AWS 上に展開することができる. また,CloudFormation ファイルを交換することで,全く同一のクラウド環境を他者が簡単に再現することも可能になる. このように,本来は物理的な実体のあるハードウェアを,プログラムによって記述し,管理するという考え方を,**Infrastructure as Code (IaC)**とよぶ.

CloudFormation を記述するには,基本的に JSON (JavaScript Object Notation) とよばれるフォーマットを使う. 次のコードは,JSON で記述された CloudFormation ファイルの一例 (抜粋) である.

json
"Resources" : {
  ...
  "WebServer": {
    "Type" : "AWS::EC2::Instance",
    "Properties": {
      "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" },
                        { "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" }, "Arch" ] } ] },
      "InstanceType"   : { "Ref" : "InstanceType" },
      "SecurityGroups" : [ {"Ref" : "WebServerSecurityGroup"} ],
      "KeyName"        : { "Ref" : "KeyName" },
      "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [
                     "#!/bin/bash -xe\n",
                     "yum update -y aws-cfn-bootstrap\n",

                     "/opt/aws/bin/cfn-init -v ",
                     "         --stack ", { "Ref" : "AWS::StackName" },
                     "         --resource WebServer ",
                     "         --configsets wordpress_install ",
                     "         --region ", { "Ref" : "AWS::Region" }, "\n",

                     "/opt/aws/bin/cfn-signal -e $? ",
                     "         --stack ", { "Ref" : "AWS::StackName" },
                     "         --resource WebServer ",
                     "         --region ", { "Ref" : "AWS::Region" }, "\n"
      ]]}}
    },
    ...
  },
  ...
},
"Resources" : {
  ...
  "WebServer": {
    "Type" : "AWS::EC2::Instance",
    "Properties": {
      "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" },
                        { "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" }, "Arch" ] } ] },
      "InstanceType"   : { "Ref" : "InstanceType" },
      "SecurityGroups" : [ {"Ref" : "WebServerSecurityGroup"} ],
      "KeyName"        : { "Ref" : "KeyName" },
      "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [
                     "#!/bin/bash -xe\n",
                     "yum update -y aws-cfn-bootstrap\n",

                     "/opt/aws/bin/cfn-init -v ",
                     "         --stack ", { "Ref" : "AWS::StackName" },
                     "         --resource WebServer ",
                     "         --configsets wordpress_install ",
                     "         --region ", { "Ref" : "AWS::Region" }, "\n",

                     "/opt/aws/bin/cfn-signal -e $? ",
                     "         --stack ", { "Ref" : "AWS::StackName" },
                     "         --resource WebServer ",
                     "         --region ", { "Ref" : "AWS::Region" }, "\n"
      ]]}}
    },
    ...
  },
  ...
},

ここでは, "WebServer" という名前のつけられた EC2 インスタンスを定義している.かなり長大で複雑な記述であるが,これによって所望のスペック・OS をもつ EC2 インスタンスを自動的に生成することが可能になる.

AWS CDK

前節で紹介した CloudFormation は,見てわかるとおり大変記述が複雑であり,またそれのどれか一つにでも誤りがあってはいけない. また,基本的に"テキスト"を書いていくことになるので,プログラミング言語で使うような変数やクラスといった便利な概念が使えない (厳密には, CloudFormation にも変数に相当するような機能は存在する). また,記述の多くの部分は繰り返しが多く,自動化できる部分も多い.

そのような悩みを解決してくれるのが, AWS Cloud Development Kit (CDK) である. CDK は Python などのプログラミング言語を使って CloudFormation を自動的に生成してくれるツールである. CDK は 2019 年にリリースされたばかりの比較的新しいツールで,日々改良が進められている (GitHub リポジトリ のリリースを見ればその開発のスピードの速さがわかるだろう). CDK は TypeScript (JavaScript), Python, Java など複数の言語でサポートされている.

CDK を使うことで,CloudFormation に相当するクラウドリソースの記述を,より親しみのあるプログラミング言語を使って行うことができる. かつ,典型的なリソース操作に関してはパラメータの多くの部分を自動で決定してくれるので,記述しなければならない量もかなり削減される.

以下に Python を使った CDK のコードの一例 (抜粋) を示す.

python
from aws_cdk import (
    core,
    aws_ec2 as ec2,
)

class MyFirstEc2(core.Stack):

    def __init__(self, scope, name, **kwargs):
        super().__init__(scope, name, **kwargs)

        vpc = ec2.Vpc(
            ... # some parameters
        )

        sg = ec2.SecurityGroup(
            ... # some parameters
        )

        host = ec2.Instance(
            self, "MyGreatEc2",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ec2.MachineImage.latest_amazon_linux(),
            vpc=vpc,
            ...
        )
from aws_cdk import (
    core,
    aws_ec2 as ec2,
)

class MyFirstEc2(core.Stack):

    def __init__(self, scope, name, **kwargs):
        super().__init__(scope, name, **kwargs)

        vpc = ec2.Vpc(
            ... # some parameters
        )

        sg = ec2.SecurityGroup(
            ... # some parameters
        )

        host = ec2.Instance(
            self, "MyGreatEc2",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ec2.MachineImage.latest_amazon_linux(),
            vpc=vpc,
            ...
        )

このコードは,一つ前に示した JSON を使った CloudFormation と実質的に同じことを記述している. とても煩雑だった CloudFormation ファイルに比べて, CDK と Python を使うことで格段に短く,わかりやすく記述できることができるのがわかるだろう.

本書の主題は,CDK を使って,コードを書きながら AWS の概念や開発方法を学んでいくことである. 後の章では CDK を使って様々なハンズオンを実施していく. 早速,最初のハンズオンでは, CDK を使って EC2 インスタンスを作成する方法を学んでいこう.

  • AWS CDK Examples: CDK を使ったプロジェクトの例が多数紹介されている. ここにある例をテンプレートに自分のアプリケーションの開発を進めるとよい.

Hands-on #1: 初めての EC2 インスタンスを起動する

ハンズオンの第一回では, CDK を使って EC2 のインスタンス(仮想サーバー)を作成し,SSH でサーバーにログインする,という演習を行う. このハンズオンを終えれば,あなたは自分だけのサーバーを AWS 上に立ち上げ,自由に計算を走らせることができるようになるのである!

準備

ハンズオンのソースコードは GitHub の handson/ec2-get-started に置いてある.

このハンズオンは,基本的に AWS の無料枠 の範囲内で実行することができる.

まずは,ハンズオンを実行するための環境を整える. これらの環境整備は,後のハンズオンでも前提となるものなので確実にミスなく行っていただきたい.

  • AWS Account: ハンズオンを実行するには個人の AWS アカウントが必要である. AWS アカウントの取得については AWS アカウントの取得 を参照のこと.
  • Python と Node.js: 本ハンズオンを実行するには,Python (3.6 以上),Node.js (12.0 以上) がインストールされていなければならない.
  • AWS CLI: AWS CLI のインストールについては, AWS CLI のインストール を参照. ここに記載されている認証鍵の設定も済ませておくこと.
  • AWS CDK: AWS CDK のインストールについては, AWS CDK のインストール を参照.
  • ソースコードのダウンロード: 本ハンズオンで使用するプログラムのソースコードを,以下のコマンドを使って GitHub からダウンロードする.
sh
$ git clone https://github.com/tomomano/learn-aws-by-coding.git
$ git clone https://github.com/tomomano/learn-aws-by-coding.git

あるいは, https://github.com/tomomano/learn-aws-by-coding のページに行って,右上のダウンロードボタンからダウンロードすることもできる.

Docker を使用する場合

Python, Node.js, AWS CDK など,ハンズオンのプログラムを実行するために必要なプログラム/ライブラリがインストール済みの Docker image を用意した. また,ハンズオンのソースコードもパッケージ済みである. Docker の使い方を知っている読者は,これを使えば,諸々のインストールをする必要なく,すぐにハンズオンのプログラムを実行できる.

使用方法については ハンズオン実行用の Docker image の使い方 を参照のこと.

SSH

SSH (secure shell) は Unix 系のリモートサーバーに安全にアクセスするためのツールである. 本ハンズオンでは, SSH を使って仮想サーバーにアクセスする. SSH に慣れていない読者のため,簡単な説明をここで行おう.

SSH による通信はすべて暗号化されているので,機密情報をインターネットを介して安全に送受信することができる. 本ハンズオンで,リモートのサーバーにアクセスするための SSH クライアントがローカルマシンにインストールされている必要がある. SSH クライアントは Linux/Mac には標準搭載されている. Windows の場合は WSL をインストールすることで SSH クライアントを利用することを推奨する (環境構築 を参照).

SSH コマンドの基本的な使い方を次に示す. <host name> はアクセスする先のサーバーの IP アドレスや DNS によるホストネームが入る. <user name> は接続する先のユーザー名である.

sh
$ ssh <user name>@<host name>
$ ssh <user name>@<host name>

SSH は平文のパスワードによる認証を行うこともできるが,より強固なセキュリティを施すため,公開鍵暗号方式(Public Key Cryptography)による認証を行うことが強く推奨されており, EC2 はこの方法でしかアクセスを許していない. 公開鍵暗号方式の仕組みについては各自勉強してほしい. 本ハンズオンにおいて大事なことは,EC2 インスタンスが公開鍵(Public key)を保持し,クライアントとなるコンピュータ(読者自身のコンピュータ)が秘密鍵(Private key)を保持する,という点である. EC2 のインスタンスには秘密鍵を持ったコンピュータのみがアクセスすることができる.逆に言うと,秘密鍵が漏洩すると第三者もサーバーにアクセスできることになるので,秘密鍵は絶対に漏洩することのないよう注意して管理する

SSH コマンドでは,ログインのために使用する秘密鍵ファイルを -i もしくは --identity_file のオプションで指定することができる. たとえば,次のように使う.

sh
$ ssh -i Ec2SecretKey.pem <user name>@<host name>
$ ssh -i Ec2SecretKey.pem <user name>@<host name>

アプリケーションの説明

このハンズオンで作成するアプリケーションの概要を figure_title に示す.

ハンズオン#1で作製するアプリケーションのアーキテクチャ

このアプリケーションではまず,VPC (Virtual Private Cloud) を使ってプライベートな仮想ネットワーク環境を立ち上げている. その VPC の public subnet の内側に,EC2 (Elatic Compute Cloud) の仮想サーバーを配置する. さらに,セキュリティのため, Security Group による EC2 インスタンスへのアクセス制限を設定している. このようにして作成された仮想サーバーに,SSH を使ってアクセスし,簡単な計算を行う.

figure_title のようなアプリケーションを,CDK を使って構築する.

早速ではあるが,今回のハンズオンで使用するプログラムを見てみよう (handson/ec2-get-started/app.py).

python
class MyFirstEc2(core.Stack):

    def __init__(self, scope: core.App, name: str, key_name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        vpc = ec2.Vpc(
            self, "MyFirstEc2-Vpc",
            max_azs=1,
            cidr="10.10.0.0/23",
            subnet_configuration=[
                ec2.SubnetConfiguration(
                    name="public",
                    subnet_type=ec2.SubnetType.PUBLIC,
                )
            ],
            nat_gateways=0,
        )

        #
        sg = ec2.SecurityGroup(
            self, "MyFirstEc2Vpc-Sg",
            vpc=vpc,
            allow_all_outbound=True,
        )
        sg.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(22),
        )

        #
        host = ec2.Instance(
            self, "MyFirstEc2Instance",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ec2.MachineImage.latest_amazon_linux(),
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            security_group=sg,
            key_name=key_name
        )
class MyFirstEc2(core.Stack):

    def __init__(self, scope: core.App, name: str, key_name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        vpc = ec2.Vpc(
            self, "MyFirstEc2-Vpc",
            max_azs=1,
            cidr="10.10.0.0/23",
            subnet_configuration=[
                ec2.SubnetConfiguration(
                    name="public",
                    subnet_type=ec2.SubnetType.PUBLIC,
                )
            ],
            nat_gateways=0,
        )

        #
        sg = ec2.SecurityGroup(
            self, "MyFirstEc2Vpc-Sg",
            vpc=vpc,
            allow_all_outbound=True,
        )
        sg.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(22),
        )

        #
        host = ec2.Instance(
            self, "MyFirstEc2Instance",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ec2.MachineImage.latest_amazon_linux(),
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            security_group=sg,
            key_name=key_name
        )
  • まず最初に,VPC を定義する.

  • 次に, security group (SG) を定義している. ここでは,任意の IPv4 のアドレスからの,ポート 22 (SSH の接続に使用される)への接続を許可している. それ以外の接続は拒絶される.

  • 最後に,上記で作った VPC と SG が付与された EC2 インスタンスを作成している. インスタンスタイプは t2.micro を選択し, Amazon Linux を OS として設定している.

それぞれについて,もう少し詳しく説明しよう.

VPC (Virtual Private Cloud)

VPC のアイコン.

VPC

VPC は AWS 上にプライベートな仮想ネットワーク環境を構築するツールである.高度な計算システムを構築するには,複数のサーバーを連動させて計算を行う必要があるが,そのような場合に互いのアドレスなどを管理する必要があり,そういった目的で VPC は有用である.

本ハンズオンでは,サーバーは一つしか起動しないので,VPC の恩恵はよく分からないかもしれない.しかし,EC2 インスタンスは必ず VPC の中に配置されなければならない,という制約があるので,このハンズオンでもミニマルな VPC を構成している.

興味のある読者のために,VPC のコードについてもう少し詳しく説明しよう.

python
vpc = ec2.Vpc(
    self, "MyFirstEc2-Vpc",
    max_azs=1,
    cidr="10.10.0.0/23",
    subnet_configuration=[
        ec2.SubnetConfiguration(
            name="public",
            subnet_type=ec2.SubnetType.PUBLIC,
        )
    ],
    nat_gateways=0,
)
vpc = ec2.Vpc(
    self, "MyFirstEc2-Vpc",
    max_azs=1,
    cidr="10.10.0.0/23",
    subnet_configuration=[
        ec2.SubnetConfiguration(
            name="public",
            subnet_type=ec2.SubnetType.PUBLIC,
        )
    ],
    nat_gateways=0,
)
  • max_azs=1 : このパラメータは,前章で説明した avaialibility zone (AZ) を設定している. このハンズオンでは,特にデータセンターの障害などを気にする必要はないので 1 にしている.

  • cidr="10.10.0.0/23" : このパラメータは,VPC 内の IPv4 のレンジを指定している. CIDR 記法については, Wikipediaなどを参照. 10.10.0.0/2310.10.0.0 から 10.10.1.255 までの 512 個の連続したアドレス範囲を指している. つまり,この VPC では最大で 512 個のユニークな IPv4 アドレスが使えることになる. 今回はサーバーは一つなので 512 個は明らかに多すぎるが,VPC はアドレスの数はどれだけ作成しても無料なので,多めに作成した.

  • subnet_configuration=... : このパラメータは,VPC にどのようなサブネットを作るか,を決めている. サブネットの種類には private subnetpublic subnet の二種類がある. private subnet は基本的にインターネットとは遮断されたサブネット環境である. インターネットと繋がっていないので,セキュリティは極めて高く, VPC 内のサーバーとのみ通信を行えばよい EC2 インスタンスはここに配置する. Public subnet とはインターネットに繋がったサブネットである. 本ハンズオンで作成するサーバーは,外から SSH でログインを行いたいので, Public subnet 内に配置する. より詳細な記述は 公式ドキュメンテーション を参照.

  • natgateways=0 : これは少し高度な内容なので省略する (興味のある読者は 公式ドキュメンテーションを参照). が,これを 0 にしておかないと,NAT Gateway の利用料金が発生してしまうので,注意!

Security Group

Security group (SG) は, EC2 インスタンスに付与することのできる仮想ファイアーウォールである. たとえば,特定の IP アドレスから来た接続を許可・拒絶したり (インバウンド・トラフィックの制限) ,逆に特定の IP アドレスへのアクセスを禁止したり (アウトバウンド・トラフィックの制限) することができる.

コードの該当部分を見てみよう.

python
sg = ec2.SecurityGroup(
    self, "MyFirstEc2Vpc-Sg",
    vpc=vpc,
    allow_all_outbound=True,
)
sg.add_ingress_rule(
    peer=ec2.Peer.any_ipv4(),
    connection=ec2.Port.tcp(22),
)
sg = ec2.SecurityGroup(
    self, "MyFirstEc2Vpc-Sg",
    vpc=vpc,
    allow_all_outbound=True,
)
sg.add_ingress_rule(
    peer=ec2.Peer.any_ipv4(),
    connection=ec2.Port.tcp(22),
)

本ハンズオンでは, SSH による外部からの接続を許容するため, sg.add_ingress_rule(peer=ec2.Peer.any_ipv4(), connection=ec2.Port.tcp(22)) により,すべての IPv4 アドレスからのポート 22 番へのアクセスを許容している. また, SSH で EC2 インスタンスにログインしたのち,インターネットからプログラムなどをダウンロードできるよう, allow_all_outbound=True のパラメータを設定している.

SSH はデフォルトでは 22 番ポートを使用するのが慣例である.

セキュリティ上の観点からは,SSH の接続は自宅や大学・職場など特定の地点からの接続のみを許す方が望ましい.

EC2 (Elastic Compute Cloud)

EC2 のアイコン.

EC2

EC2 は AWS 上に仮想サーバーを立ち上げるサービスである. 個々の起動状態にある仮想サーバーのことをインスタンス (instance) とよぶ (しかし,口語的なコミュニケーションにおいては,サーバーとインスタンスという言葉は相互互換的に用いられることが多い).

EC2 では用途に応じて様々なインスタンスタイプが提供されている. table_title に,代表的なインスタンスタイプの例を挙げる (執筆時点での情報). EC2 のインスタンスタイプのすべてのリストは 公式ドキュメンテーション "Amazon EC2 Instance Types" で見ることができる.

EC2 instance types
InstancevCPUMemory (GiB)Network bandwidth (Gbps)Price per hour ($)

t2.micro

1

1

-

0.0116

t2.small

1

2

-

0.023

t2.medium

2

4

-

0.0464

c5.24xlarge

96

192

25

4.08

c5n.18xlarge

72

192

100

3.888

x1e.16xlarge

64

1952

10

13.344

table_title からわかるように, CPU は 1 コアから 96 コアまで,メモリーは 1GB から 2TB 以上まで,ネットワーク帯域は最大で 100Gbps まで,幅広く選択することができる. また,時間あたりの料金は,CPU・メモリーの占有数にほぼ比例する形で増加する. EC2 はサーバーの起動時間を秒単位で記録しており,利用料金は使用時間に比例する形で決定される. 例えば, t2.medium のインスタンスを 10 時間起動した場合,0.0464 * 10 = 0.464 ドルの料金が発生する.

AWS には 無料利用枠 というものがあり, t2.micro であれば月に 750 時間までは無料で利用することができる.

table_title の価格は us-east-1 のものである. リージョンによって多少価格設定が異なる.

上記で t2.micro の $0.0116 / hour という金額は, On-demand インスタンスというタイプを選択した場合の価格である. EC2 ではほかに, Spot instance とよばれるインスタンスも存在しする. Spot instance は,AWS のデータセンターの負荷が増えた場合,ユーザーのプログラムが実行中であっても AWS の判断により強制シャットダウンされる,という不便さを抱えているのだが,その分大幅に安い料金設定になっている. AWS で一時的に生じた余剰な空き CPU をユーザーに割安で貸し出す,という発想である. 科学計算やウェブサーバーなどの用途でコストを削減する目的で, Spot Instance を活用する事例も多数報告されている.

EC2 インスタンスを定義しているコードの該当部分を見てみよう.

python
host = ec2.Instance(
    self, "MyFirstEc2Instance",
    instance_type=ec2.InstanceType("t2.micro"),
    machine_image=ec2.MachineImage.latest_amazon_linux(),
    vpc=vpc,
    vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
    security_group=sg,
    key_name=key_name
)
host = ec2.Instance(
    self, "MyFirstEc2Instance",
    instance_type=ec2.InstanceType("t2.micro"),
    machine_image=ec2.MachineImage.latest_amazon_linux(),
    vpc=vpc,
    vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
    security_group=sg,
    key_name=key_name
)

ここでは, t2.micro というインスタンスタイプを選択している. さらに, machine_image として, Amazon Linux を選択している (Machine image は OS と似た概念である. Machine image については, Hands-on #2: AWS でディープラーニングを実践 でより詳しく触れる). さらに,上で定義した VPC, SG をこのインスタンスに付与している.

以上が,今回使用するプログラムの簡単な解説であった. ミニマルな形のプログラムではあるが,仮想サーバーを作成するのに必要なステップがおわかりいただけただろうか?

プログラムを実行する

さて,ハンズオンのコードの理解ができたところで,プログラムを実際に実行してみよう.繰り返しになるが, 準備 での準備ができていることが前提である.

Python の依存ライブラリのインストール

まずは,Python の依存ライブラリをインストールする.以下では,Python のライブラリを管理するツールとして, venv を使用する.

まずは, handson/ec2-get-started のディレクトリに移動しよう.

sh
$ cd handson/ec2-get-started
$ cd handson/ec2-get-started

ディレクトリを移動したら, venv で新しい仮想環境を作成し,インストールを実行する.

sh
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

これで Python の環境構築は完了だ.

venv の簡単な説明は Python クイックガイド に記述してある.

環境によっては pip ではなく pip3 あるいは python3 -m pip に置き換える必要がある.

AWS のシークレットキーをセットする

AWS CLI および AWS CDK を使うには, AWS のシークレットキーが設定されている必要がある. シークレットキーの発行については AWS のシークレットキーの作成 を参照のこと. シークレットキーを発行したら, AWS CLI のインストール を参照し,コマンドラインの設定を行う.

手順をここに短く要約すると,一つ目の方法は AWS_ACCESS_KEY_ID などの環境変数を設定するやり方である. もう一つの方法は, ~/.aws/credentials に認証情報を保存しておく方式である. シークレットキーの設定は AWS CLI/CDK を使用するうえで共通のステップになるので,しっかりと理解しておくように.

SSH 鍵を生成

EC2 インスタンスには SSH を使ってログインする. EC2 インスタンスを作成するのに先行して,今回のハンズオンで専用に使う SSH の公開鍵・秘密鍵のペアを準備する必要がある.

次の AWS CLI コマンドにより, HirakeGoma という名前のついた鍵を生成する.

sh
$ export KEY_NAME="HirakeGoma"
$ aws ec2 create-key-pair --key-name ${KEY_NAME} --query 'KeyMaterial' --output text > ${KEY_NAME}.pem
$ export KEY_NAME="HirakeGoma"
$ aws ec2 create-key-pair --key-name ${KEY_NAME} --query 'KeyMaterial' --output text > ${KEY_NAME}.pem

このコマンドを実行すると,現在のディレクトリに HirakeGoma.pem というファイルが作成される.これが,サーバーにアクセスするための秘密鍵である. SSH でこの鍵を使うため, ~/.ssh/ のディレクトリに鍵を移動する. さらに,秘密鍵が書き換えられたり第三者に閲覧されないよう,ファイルのアクセス権限を 400 に設定する.

sh
$ mv HirakeGoma.pem ~/.ssh/
$ chmod 400 ~/.ssh/HirakeGoma.pem
$ mv HirakeGoma.pem ~/.ssh/
$ chmod 400 ~/.ssh/HirakeGoma.pem

デプロイを実行

これまでのステップで, EC2 インスタンスをデプロイするための準備が整った! 早速,次のコマンドによりアプリケーションを AWS にデプロイしよう. -c key_name="HirakeGoma" というオプションで,先ほど生成した HirakeGoma という名前の鍵を使うよう指定している.

sh
$ cdk deploy -c key_name="HirakeGoma"
$ cdk deploy -c key_name="HirakeGoma"

このコマンドを実行すると, VPC, EC2 などが AWS 上に展開される. そして,コマンドの出力の最後に figure_title のような出力が得られるはずである. 出力の中で InstancePublicIp に続く数字が,起動したインスタンスのパブリック IP アドレスである. IP アドレスはデプロイごとにランダムなアドレスが割り当てられる.

CDKデプロイ実行後の出力

SSH でログイン

早速,SSH  で接続してみよう.

sh
$ ssh -i ~/.ssh/HirakeGoma.pem ec2-user@<IP address>
$ ssh -i ~/.ssh/HirakeGoma.pem ec2-user@<IP address>

-i オプションで,先ほど生成した秘密鍵を指定している. EC2 インスタンスにはデフォルトで ec2-user という名前のユーザーが作られているので,それを使用する. 最後に, <IP address> の部分は自身が作成した EC2 インスタンスの IP アドレスで置き換える (12.345.678.9 など).

ログインに成功すると, figure_title のような画面が表示される. リモートのサーバーにログインしているので,プロンプトが [ec2-user@ip-10-10-1-217 ~]$ のようになっていることを確認しよう.

SSH で EC2 インスタンスにログイン

おめでとう!これで,めでたく AWS 上に EC2 仮想サーバーを起動し,リモートからアクセスできるようになった!

起動した EC2 インスタンスで遊んでみる

せっかく新しいインスタンスを起動したので,少し遊んでみよう.

ログインした EC2 インスタンスで,次のコマンドを実行してみよう. CPU の情報を取得することができる.

sh
$ cat /proc/cpuinfo

processor       : 0
vendor_id       : GenuineIntel
cpu family      : 6
model           : 63
model name      : Intel(R) Xeon(R) CPU E5-2676 v3 @ 2.40GHz
stepping        : 2
microcode       : 0x43
cpu MHz         : 2400.096
cache size      : 30720 KB
$ cat /proc/cpuinfo

processor       : 0
vendor_id       : GenuineIntel
cpu family      : 6
model           : 63
model name      : Intel(R) Xeon(R) CPU E5-2676 v3 @ 2.40GHz
stepping        : 2
microcode       : 0x43
cpu MHz         : 2400.096
cache size      : 30720 KB

次に,実行中のプロセスやメモリの消費を見てみよう.

sh
$  top -n 1

top - 09:29:19 up 43 min,  1 user,  load average: 0.00, 0.00, 0.00
Tasks:  76 total,   1 running,  51 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.3%us,  0.3%sy,  0.1%ni, 98.9%id,  0.2%wa,  0.0%hi,  0.0%si,  0.2%st
Mem:   1009140k total,   270760k used,   738380k free,    14340k buffers
Swap:        0k total,        0k used,        0k free,   185856k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
    1 root      20   0 19696 2596 2268 S  0.0  0.3   0:01.21 init
    2 root      20   0     0    0    0 S  0.0  0.0   0:00.00 kthreadd
    3 root      20   0     0    0    0 I  0.0  0.0   0:00.00 kworker/0:0
$  top -n 1

top - 09:29:19 up 43 min,  1 user,  load average: 0.00, 0.00, 0.00
Tasks:  76 total,   1 running,  51 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.3%us,  0.3%sy,  0.1%ni, 98.9%id,  0.2%wa,  0.0%hi,  0.0%si,  0.2%st
Mem:   1009140k total,   270760k used,   738380k free,    14340k buffers
Swap:        0k total,        0k used,        0k free,   185856k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
    1 root      20   0 19696 2596 2268 S  0.0  0.3   0:01.21 init
    2 root      20   0     0    0    0 S  0.0  0.0   0:00.00 kthreadd
    3 root      20   0     0    0    0 I  0.0  0.0   0:00.00 kworker/0:0

t2.micro インスタンスなので, 1009140k = 1GB のメモリーがあることがわかる.

今回起動したインスタンスには Python 2 はインストール済みだが, Python 3 は入っていない. Python 3.6 のインストールを行ってみよう. インストールは簡単である.

sh
$ sudo yum update -y
$ sudo yum install -y python36
$ sudo yum update -y
$ sudo yum install -y python36

インストールした Python を起動してみよう.

sh
$ python3
Python 3.6.10 (default, Feb 10 2020, 19:55:14)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
$ python3
Python 3.6.10 (default, Feb 10 2020, 19:55:14)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Python のインタープリタが起動した! Ctrl + D あるいは exit() と入力することで,インタープリタを閉じることができる.

さて,サーバーでのお遊びはこんなところにしておこう (興味があれば各自いろいろと試してみると良い) . 次のコマンドでログアウトする.

sh
$ exit
$ exit

AWS コンソールから確認

これまでは,すべてコマンドラインから EC2 に関連する操作を行ってきた. EC2 インスタンスの状態を確認したり,サーバーをシャットダウンするなどの操作は,AWS コンソールから実行することもできる. 軽くこれを紹介しよう.

まず,ウェブブラウザを開いて AWS コンソールにログインする. ログインしたら, Services から EC2 を検索(選択)する. 次に,左のサイドバーの Instances とページをたどる. すると, figure_title のような画面が得られるはずである. この画面で,自分のアカウントの管理下にあるインスタンスを確認できる. 同様に,VPC・SG についてもコンソールから確認できる.

EC2 コンソール画面

コンソール右上で,正しいリージョン (今回の場合は ap-northeast-1, Tokyo) が選択されているか,注意する!

前章で CloudFormation について触れたが,今回デプロイしたアプリケーションも,CloudFormation のスタックとして管理されている. スタック (stack) とは, AWS リソースの集合のことを指す. 今回の場合は, VPC/EC2/SG などがスタックの中に含まれている. コンソールで CloudFormation のページに行ってみよう (figure_title).

CloudFormation コンソール画面

"MyFirstEc2" という名前のスタックがあることが確認できる. クリックをして中身を見てみると,EC2, VPC などのリソースがこのスタックに紐付いていることがわかる.

スタックを削除

これにて,第一回のハンズオンで説明すべき事柄はすべて完了した. 最後に,使わなくなったスタックを削除しよう. スタックの削除には,二つの方法がある.

一つ目の方法は,前節の Cloudformation のコンソール画面で, "Delete" ボタンを押すことである (figure_title). すると,スタックの状態が "DELETE_IN_PROGRESS" に変わり,削除が完了すると CloudFormation のスタックの一覧から消える.

CloudFormationコンソール画面から,スタックを削除

二つ目の方法は,コマンドラインから行う方法である. 先ほど,デプロイを行ったコマンドラインに戻ろう. そうしたら,次のコマンドを実行する.

sh
$ cdk destroy
$ cdk destroy

このコマンドを実行すると,スタックの削除が始まる. 削除した後は,VPC, EC2 など,すべて跡形もなく消え去っていることを自身で確かめよう. CloudFormation を用いることで関連するすべての AWS リソースを一度に管理・削除することができるので,大変便利である.

スタックの削除は各自で必ず行うこと! 行わなかった場合, EC2 インスタンスの料金が発生し続けることになる!

また,本ハンズオンのために作成した SSH 鍵ペアも不要なので,削除しておく. まず, EC2 側に登録してある公開鍵を削除する. これも,コンソールおよびコマンドラインの二つの方法で実行できる.

コンソールから実行するには, EC2 の画面に行き,左のサイドバーの Key Pairs を選択する. 鍵の一覧が表示されるので, HirakeGoma とある鍵にチェックを入れ,画面右上の Actions から, Delete を実行する (figure_title).

EC2でSSH鍵ペアを削除

コマンドラインから実行するには,次のコマンドを使う.

sh
$ aws ec2 delete-key-pair --key-name "HirakeGoma"
$ aws ec2 delete-key-pair --key-name "HirakeGoma"

最後に,ローカルのコンピュータから鍵を削除する.

sh
$ rm -f ~/.ssh/HirakeGoma.pem
$ rm -f ~/.ssh/HirakeGoma.pem

これで,クラウドの片付けもすべて終了だ.

なお,頻繁に EC2 インスタンスを起動したりする場合は,いちいち SSH 鍵を削除する必要はない.

小括

ここまでが,本書の第一部の内容である. 盛りだくさんの内容であったが,ついてこれたであろうか?

クラウド概論 では,クラウドの定義と用語の説明を行ったあと,なぜクラウドを使うのか,という点を議論した. 続いて AWS 入門 では,クラウドを学ぶ具体的なプラットフォームとして AWS を取り上げ, AWS を使用するにあたり最低限必要な知識と用語の説明を行った. さらに, Hands-on #1: 初めての EC2 インスタンスを起動する のハンズオンでは AWS CLI と AWS CDK を使って,自身のプライベートなサーバーを AWS 上に立ち上げる演習を行った.

これらを通じて,いかに簡単に (たった数行のコマンドで!) 仮想サーバーを立ち上げたり,削除したりすることができるか,体験できただろう. 筆者は,クラウド概論 でクラウドの最も重要な側面はダイナミックに計算リソースを拡大・縮小できることである,と述べた. この言葉の意味が,ハンズオンを通じてより明らかになっただろうか? ここで学んだ技術を少し応用するだけで,自分のウェブページをホストする仮想サーバーを作成したり,大量のコアを搭載した EC2 インスタンスを用意して科学計算を実行するなど,いろいろなアプリケーションが実現できる.

次章からは,今回学んだクラウドの技術を基に,より現実に即した問題を解くことを体験してもらう. お楽しみに!

クラウドで行う科学計算・機械学習

計算機が発達した現代では,計算機によるシミュレーションやビッグデータの解析は,科学・エンジニアリングの研究の主要な柱である. これらの大規模な計算を実行するには,クラウドは最適である. 本章から始まる第二部では,どのようにしてクラウド上で科学計算を実行するのかを,ハンズオンとともに体験してもらう. 科学計算の具体的な題材として,今回は機械学習(深層学習)を取り上げる.

なお,本書では PyTorch ライブラリを使って深層学習のアルゴリズムを実装するが,深層学習および PyTorch の知識は不要である. 講義ではなぜ・どうやって深層学習をクラウドで実行するかに主眼を置いているので,実行するプログラムの詳細には立ち入らない. 将来,自分で深層学習を使う機会が来たときに,詳しく学んでもらいたい.

なぜ機械学習をクラウドで行うのか?

2010 年頃に始まった第三次 AI ブームのおかげで,学術研究だけでなく社会・ビジネスの文脈でも機械学習に高い関心が寄せられている. とくに,深層学習 (ディープラーニング) とよばれる多層のレイヤーからなるニューラルネットワークを用いたアルゴリズムは,画像認識や自然言語処理などの分野で圧倒的に高い性能を実現し,革命をもたらしている.

深層学習の特徴は,なんといってもそのパラメータの多さである. 層が深くなるほど,層間のニューロンを結ぶ重みパラメータの数が増大していく. たとえば,最新の言語モデルである GPT-3 には1750 億個ものパラメータが含まれている. このような膨大なパラメータを有することで,深層学習は高い表現力と汎化性能を実現しているのである.

GPT-3 に限らず,最近の SOTA (State-of-the-art) の性能を達成するニューラルネットワークでは,百万から億のオーダーのパラメータを内包することは頻繁になってきている. そのような巨大なニューラルネットを訓練 (最適化) させるのは,当然のことながら膨大な計算コストがかかる. 結果として,ひとつの計算機では丸一日以上の時間がかかる場合も珍しくない. 深層学習の発展の速度は目覚ましく,研究・ビジネス両方の観点からも,いかにスループットよくニューラルネットワークの最適化を行えるかが鍵となってくる. そのような問題を解決するのにとても有効な手段が,クラウドである! Hands-on #1: 初めての EC2 インスタンスを起動する でその片鱗を見たように,クラウドを使用することでゼロから数千に至るまでの数のインスタンスを動的に起動し,並列に計算を実行することができる. さらに,深層学習を加速させる目的で,深層学習の演算に専用設計された計算チップ (GPU など) がある. クラウドを利用すると,そのような専用計算チップも無尽蔵に利用することができる. 事実,先述した GPT-3 の学習も,詳細は明かされていないが,Microsoft 社のクラウドを使って行われたと報告されている.

GPU による深層学習の高速化

深層学習の計算で欠かすことのできない技術として, GPU (Graphics Processing Unit) について少し説明する.

GPU は,その名のとおり,元々はコンピュータグラフィックスを出力するための専用計算チップである. CPU (Central Processing Unit) に対し,グラフィックスの演算に特化した設計がなされている. 身近なところでは, XBox や PS5 などのゲームコンソールなどに搭載されているし,ハイエンドなノート型・デスクトップ型計算機にも搭載されていることがある. コンピュータグラフィックスでは,スクリーンにアレイ状に並んだ数百万個の画素をビデオレート (30 fps) 以上で処理する必要がある. そのため,GPU はコアあたりの演算能力は比較的小さいかわりに,チップあたり数百から数千のコアを搭載しており (figure_title),スクリーンの画素を並列的に処理することで,リアルタイムでの描画を実現している.

GPUのアーキテクチャ.GPUには数百から数千の独立した計算コアが搭載されている. (画像出典: https://devblogs.nvidia.com/nvidia-turing-architecture-in-depth/)

このように,コンピュータグラフィクスの目的で生まれた GPU だが,2010 年前後から,その高い並列計算能力をグラフィックス以外の計算 (科学計算など) に用いるという流れ (General-purpose computing on GPU; GPGPU) が生まれた. GPU のコアは,その設計から,行列の計算など,単純かつ規則的な演算が得意であり,そのような演算に対しては数個程度のコアしかもたない CPU に比べて圧倒的に高い計算速度を実現することができる. 現在では GPGPU は分子動力学や気象シミュレーション,そして機械学習など多くの分野で使われている.

ディープラーニングで最も頻繁に起こる演算が,ニューロンの出力を次の層のニューロンに伝える畳み込み (Convolution) 演算である (figure_title). 畳み込み演算は,まさに GPU が得意とする演算であり, CPU ではなく GPU を用いることで学習を飛躍的に (最大で数百倍程度) 加速させることができる.

ニューラルネットワークにおける畳み込み演算.

このように GPU は機械学習の計算で欠かせないものであるが,なかなか高価である. たとえば,科学計算・機械学習に専用設計された NVIDIA 社の Tesla V100 というチップは,一台で約百万円の価格が設定されている. 機械学習を始めるのに,いきなり百万円の投資はなかなか大きい. だが,クラウドを使えば,初期コスト0で GPU を使用することができる.

機械学習を行うのに, V100 が必ずしも必要というわけではない. むしろ,研究者などでしばしば行われるのは,コンピュータゲームに使われるグラフィックス用の GPU を買ってきて (NVIDIA GeForce シリーズなど),開発のときはをそれを用いる,というアプローチである. グラフィックス用のいわゆる"コンシューマ GPU"は,市場の需要が大きいおかげで,10 万円前後の価格で購入することができる. V100 と比べると,コンシューマ GPU はコアの数が少なかったり,メモリーが小さかったりなどで劣る点があるが, それらを除いては計算能力にとくに制限があるわけではなく,開発の段階では十分な性能である場合がほとんどである. プログラムができあがって,ビッグデータの解析や,モデルをさらに大きくしたいときなどに,クラウドは有効だろう.

クラウドで GPU を使うには, GPU が搭載された EC2 インスタンスタイプ (P3, P2, G3, G4 など) を選択しなければならない. table_title に,代表的な GPU 搭載のインスタンスタイプを挙げる (執筆時点での情報).

GPUを搭載したEC2インスタンスタイプ
InstanceGPUsGPU modelGPU Mem (GiB)vCPUMem (GiB)Price per hour ($)

p3.2xlarge

1

NVIDIA V100

16

8

61

3.06

p3n.16xlarge

8

NVIDIA V100

128

64

488

24.48

p2.xlarge

1

NVIDIA K80

12

4

61

0.9

g4dn.xlarge

1

NVIDIA T4

16

4

16

0.526

table_title からわかるとおり, CPU のみのインスタンスと比べると少し高い価格設定になっている. また,古い世代の GPU (V100 に対しての K80) はより安価な価格で提供されている. 1 インスタンスあたりの GPU の搭載数は 1 台から最大で 8 台まで選択することが可能である.

GPU を搭載した一番安いインスタンスタイプは, g4dn.xlarge であり,これには廉価かつ省エネルギー設計の NVIDIA T4 が搭載されている. 後のハンズオンでは,このインスタンスを使用して,ディープラーニングの計算を行ってみる.

table_title の価格は us-east-1 のものである. リージョンによって多少価格設定が異なる.

V100 を一台搭載した p3.2xlarge の利用料金は一時間あたり $3.06 である. V100 が約百万円で売られていることを考えると,約 3000 時間 (= 124 日間),通算で計算を行った場合に,クラウドを使うよりも V100 を自分で買ったほうがお得になる,という計算になる (実際には,自前で V100 を用意する場合は, V100 だけでなく, CPU やネットワーク機器,電気使用料も必要なので,百万円よりもさらにコストがかかる).

GPT-3 で使われた計算リソースの詳細は論文でも明かされていないのだが, Lambda 社のブログで興味深い考察が行われている (Lambda 社は機械学習に特化したクラウドサービスを提供している).

記事によると,1750 億のパラメータを訓練するには,一台の GPU (NVIDIA V100) を用いた場合,342 年の月日と 460 万ドルのクラウド利用料が必要となる,とのことである. GPT-3 のチームは,複数の GPU に処理を分散することで現実的な時間のうちに訓練を完了させたのであろうが,このレベルのモデルになってくるとクラウド技術の限界を攻めないと達成できないことは確かである.

深層学習を詳しく勉強したい人には以下の参考書を推薦したい. 深層学習の基礎的な概念や理論は普遍的であるが,この分野は日進月歩なので,常に最新の情報を取り入れることを忘れずに.

Hands-on #2: AWS でディープラーニングを実践

準備

ハンズオン第二回では, GPU を搭載した EC2 インスタンスを起動し,深層学習モデルの学習と推論を実行する演習を行う.

ハンズオンのソースコードは GitHub の handson/mnist に置いてある.

本ハンズオンの実行には,第一回ハンズオンで説明した準備 (準備) が整っていることを前提とする. それ以外に必要な準備はない.

初期状態の AWS アカウントでは, GPU 搭載の G タイプのインスタンスの起動上限が 0 になっていることがある. これを確認するには, AWS コンソールから EC2 の画面を開き,左のメニューから Limits を選択する. その中の Running On-Demand All G instances という数字が G インスタンスの起動上限を表している.

もし,これが 0 になっていた場合は, AWS の自動申請フォームから上限緩和のリクエストを送る必要がある. 詳しくは 公式ドキュメンテーション "Amazon EC2 service quotas" を参照のこと.

このハンズオンは, g4dn.xlarge タイプの EC2 インスタンスを使うので,東京 (ap-northeast-1) リージョンでは 0.71 $/hour のコストが発生する.

AWS Educate Starter Account を使用している読者へ: 執筆時点においては, Starter Account には GPU 搭載型インスタンスを起動できないという制限が設けられている. したがって, Starter Account のユーザーはこのハンズオンを実行することはできない. 興味のある読者は,制限のない一般アカウントを自分自身で取得する必要があることに注意.

アプリケーションの説明

このハンズオンで作成するアプリケーションの概要を figure_title に示す.

ハンズオン#2で作製するアプリケーションのアーキテクチャ

図の多くの部分が,第一回ハンズオンで作成したアプリケーションと共通していることに気がつくだろう. 少しの変更で,簡単にディープラーニングを走らせる環境を構築することができるのである!主な変更点は次の3点である.

  • GPU を搭載した g4dn.xlarge インスタンスタイプを使用

  • ディープラーニングに使うプログラムがあらかじめインストールされた DLAMI (後述) を使用

  • SSH にポートフォワーディングのオプションつけてサーバーに接続し,サーバーで起動している Jupyter Notebook (後述) を使ってプログラムを書いたり実行したりする

ハンズオンで使用するプログラムのコードをみてみよう handson/mnist/app.py). コードは第一回目とほとんど共通である.変更点のみ解説を行う.

python
class Ec2ForDl(core.Stack):

    def __init__(self, scope: core.App, name: str, key_name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        vpc = ec2.Vpc(
            self, "Ec2ForDl-Vpc",
            max_azs=1,
            cidr="10.10.0.0/23",
            subnet_configuration=[
                ec2.SubnetConfiguration(
                    name="public",
                    subnet_type=ec2.SubnetType.PUBLIC,
                )
            ],
            nat_gateways=0,
        )

        sg = ec2.SecurityGroup(
            self, "Ec2ForDl-Sg",
            vpc=vpc,
            allow_all_outbound=True,
        )
        sg.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(22),
        )

        host = ec2.Instance(
            self, "Ec2ForDl-Instance",
            instance_type=ec2.InstanceType("g4dn.xlarge"), #
            machine_image=ec2.MachineImage.generic_linux({
                "us-east-1": "ami-060f07284bb6f9faf",
                "ap-northeast-1": "ami-09c0c16fc46a29ed9"
            }), #
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            security_group=sg,
            key_name=key_name
        )
class Ec2ForDl(core.Stack):

    def __init__(self, scope: core.App, name: str, key_name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        vpc = ec2.Vpc(
            self, "Ec2ForDl-Vpc",
            max_azs=1,
            cidr="10.10.0.0/23",
            subnet_configuration=[
                ec2.SubnetConfiguration(
                    name="public",
                    subnet_type=ec2.SubnetType.PUBLIC,
                )
            ],
            nat_gateways=0,
        )

        sg = ec2.SecurityGroup(
            self, "Ec2ForDl-Sg",
            vpc=vpc,
            allow_all_outbound=True,
        )
        sg.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(22),
        )

        host = ec2.Instance(
            self, "Ec2ForDl-Instance",
            instance_type=ec2.InstanceType("g4dn.xlarge"), #
            machine_image=ec2.MachineImage.generic_linux({
                "us-east-1": "ami-060f07284bb6f9faf",
                "ap-northeast-1": "ami-09c0c16fc46a29ed9"
            }), #
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            security_group=sg,
            key_name=key_name
        )
  • ここで, g4dn.xlarge インスタンスタイプを選択している (第一回では, CPU のみの t2.micro だった). g4dn.xlarge のインスタンスタイプは, クラウドで行う科学計算・機械学習 ですでに触れた通り, NVIDIA T4 と呼ばれる廉価版モデルの GPU を搭載したインスタンスである. CPU は 4 core, メインメモリーは 16GB が割り当てあられている.

  • ここでは,Deep Learning 用の諸々のソフトウェアがプリンストールされた AMI (Deep Learning Amazon Machine Image; DLAMI) を選択している (第一回では,Amazon Linux という AMI を使用していた). 使用する AMI の ID は リージョンごとに指定する必要があり,ここでは us-east-1ap-northeast-1 でそれぞれ定義している.

DLAMI という新しい概念が出てきたので,説明しよう.

AMI が us-east-1ap-northeast-1 でしか定義されていないので,提供されているコードはこの二つのリージョンのみでデプロイ可能である. もしほかのリージョンを利用したい場合は, AMI の ID を自身で検索し,コードに書き込む必要がある.

DLAMI (Deep Learning Amazon Machine Image)

AMI (Amazon Machine Image) とは,大まかには OS (Operating System) に相当する概念である. 当然のことながら, OS がなければコンピュータはなにもできないので,EC2 インスタンスを起動するときには必ずなにかの OS を"インストール"する必要がある. EC2 が起動したときにロードされる OS に相当するものが, AMI である. AMI には,たとえば Ubuntu などの Linux 系 OS に加えて,Windows Server を選択することもできる. また, EC2 での使用に最適化された Amazon Linux という AMI も提供されている.

しかしながら, AMI を単なる OS と理解するのは過剰な単純化である. AMI には,ベースとなる (空っぽの) OS を選択することもできるが,それに加えて,各種のプログラムがインストール済みの AMI も定義することができる. 必要なプログラムがインストールされている AMI を見つけることができれば,自身でインストールを行ったり環境設定したりする手間が大幅に省ける. 具体例を挙げると,ハンズオン第一回では EC2 インスタンスに Python 3.6 をインストールする例を示したが,そのような操作をインスタンスが起動するたびに行うのは手間である!

AMI は, AWS 公式のものに加えて,サードパーティから提供されているものもある. また,自分自身の AMI を作って登録することも可能である (参考). AMI は EC2 のコンソールから検索することが可能である. あるいは,AWS CLI を使って,次のコマンドでリストを取得することができる (参考).

sh
$ aws ec2 describe-images --owners amazon
$ aws ec2 describe-images --owners amazon

ディープラーニングで頻繁に使われるプログラムがあらかじめインストールしてある AMI が, DLAMI (Deep Learning AMI) である. DLAMI には TensorFlow, PyTorch などの人気の高いディープラーニングのフレームワーク・ライブラリがすでにインストールされているため, EC2 インスタンスを起動してすぐさまディープラーニングの計算を実行できる.

本ハンズオンでは, Amazon Linux 2 をベースにした DLAMI を使用する (AMI ID = ami-09c0c16fc46a29ed9.この AMI は ap-northeast-1 でしか使用できない点に注意). AWS CLI を使って,この AMI の詳細情報を取得してみよう.

sh
$ aws ec2 describe-images --owners amazon --image-ids "ami-09c0c16fc46a29ed9" --region ap-northeast-1
$ aws ec2 describe-images --owners amazon --image-ids "ami-09c0c16fc46a29ed9" --region ap-northeast-1

AMI ID = ami-09c0c16fc46a29ed9 の詳細情報

figure_title のような出力が得られるはずである.得られた出力から,この DLAMI には PyTorch のバージョン 1.4.0 と 1.5.0 がインストールされていることがわかる. この DLAMI を使って,早速ディープラーニングの計算を実行してみよう.

DLAMI には具体的には何がインストールされているのだろうか? 興味のある読者のために,簡単な解説をしよう (参考: 公式ドキュメンテーション "What Is the AWS Deep Learning AMI?").

最も low-level なレイヤーとしては, GPU ドライバー がインストールされている. GPU ドライバーなしには OS は GPU とコマンドのやり取りをすることができない. 次のレイヤーが CUDAcuDNN である. CUDA は, NVIDIA 社が開発した, GPU 上で汎用コンピューティングを行うための言語であり, C++ 言語を拡張したシンタックスを備える. cuDNN は CUDA で書かれたディープラーニングのライブラリであり,n 次元の畳み込みなどの演算が実装されている. ここまでが, "Base" とよばれるタイプの DLAMI の中身である.

これに加えて, "Conda" とよばれるタイプには, "Base" のプログラム基盤の上に, TensorFlowPyTorch などのライブラリがインストールされている. さらに, Anaconda による仮想環境を使うことによって, TensorFlow の環境・ PyTorch の環境・ MxNet の環境など,フレームワークを簡単に切り替えることができる (これについては,後のハンズオンで触れる). また, Jupyter Notebook もインストール済みである.

スタックのデプロイ

スタックの中身が理解できたところで,早速スタックをデプロイしてみよう.

デプロイの手順は,ハンズオン 1 とほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). それぞれのコマンドの意味を忘れてしまった場合は,ハンズオン 1 に戻って復習していただきたい. シークレットキーの設定も忘れずに (AWS CLI のインストール).

sh
# プロジェクトのディレクトリに移動
$ cd handson/mnist

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# SSH鍵を生成
$ export KEY_NAME="HirakeGoma"
$ aws ec2 create-key-pair --key-name ${KEY_NAME} --query 'KeyMaterial' --output text > ${KEY_NAME}.pem
$ mv HirakeGoma.pem ~/.ssh/
$ chmod 400 ~/.ssh/HirakeGoma.pem

# デプロイを実行
$ cdk deploy -c key_name="HirakeGoma"
# プロジェクトのディレクトリに移動
$ cd handson/mnist

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# SSH鍵を生成
$ export KEY_NAME="HirakeGoma"
$ aws ec2 create-key-pair --key-name ${KEY_NAME} --query 'KeyMaterial' --output text > ${KEY_NAME}.pem
$ mv HirakeGoma.pem ~/.ssh/
$ chmod 400 ~/.ssh/HirakeGoma.pem

# デプロイを実行
$ cdk deploy -c key_name="HirakeGoma"

ハンズオン 1 で作成した SSH 鍵の削除を行わなかった場合は, SSH 鍵を改めて作成する必要はない. 逆に言うと,同じ名前の SSH がすでに存在する場合は,鍵生成のコマンドはエラーを出力する.

デプロイのコマンドが無事に実行されれば, figure_title のような出力が得られるはずである.AWS により割り振られた IP アドレス (InstancePublicIp に続く文字列) をメモしておこう.

CDKデプロイ実行後の出力

ログイン

早速,デプロイしたインスタンスに SSH でログインしてみよう. ここでは,この後で使う Jupyter Notebook に接続するため,ポートフォワーディング (port forwarding) のオプション (-L) をつけてログインする.

sh
$ ssh -i ~/.ssh/HirakeGoma.pem -L localhost:8931:localhost:8888 ec2-user@<IP address>
$ ssh -i ~/.ssh/HirakeGoma.pem -L localhost:8931:localhost:8888 ec2-user@<IP address>

ポートフォワーディングとは,クライアントマシンの特定のアドレスへの接続を, SSH の暗号化された通信を介して,リモートマシンの特定のアドレスへ転送する,という意味である. このコマンドの -L localhost:8931:localhost:8888 は,自分のローカルマシンの localhost:8931 へのアクセスを,リモートサーバーの localhost:8888 のアドレスに転送せよ,という意味である (: につづく数字は TCP/IP ポートの番号を意味している). リモートサーバーのポート 8888 には,後述する Jupyter Notebook が起動している. したがって,ローカルマシンの localhost:8931 にアクセスすることで,リモートサーバーの Jupyter Notebook にアクセスすることができるのである (figure_title). このような SSH による接続方式をトンネル接続とよぶ.

SSH のポートフォワーディングによる Jupyter Notebook へのアクセス

ポートフォワーディングのオプションで,ポートの番号 (:8931, :8888 など) には 1 から 65535 までの任意の整数を指定できる. しかし,たとえば ポート 22 (SSH) やポート 80 (HTTP) など,いくつかすでに使われているポート番号もあることに注意する. また, Jupyter Notebook はデフォルトではポート 8888 番を使用する. したがって,リモート側のポート番号は,8888 を使うのがよい.

SSH ログインコマンドの <IP address> 部分は自身のインスタンスの IP アドレスを代入することを忘れずに.

本書の提供している Docker を使ってデプロイを実行した人へ

SSH によるログインは, Docker の外 (すなわちクライアントマシン本体) から行わなければならない. なぜなら,Jupyter を開くウェブブラウザは Docker の外にあるからである.

その際,秘密鍵を Docker の外にもってこなければならない. 手っ取り早い方法は, cat ~/.ssh/HirakeGoma と打って,出力結果をコピーしてホストマシンのファイルに書き込む方法である. あるいは -v オプションをつけて,ファイルシステムをマウントしてもよい (詳しくは Docker 公式ドキュメンテーション "Use volumes" を参照).

SSH によるログインができたら,早速, GPU の状態を確認してみよう. 次のコマンドを実行する.

sh
$ nvidia-smi
$ nvidia-smi

figure_title のような出力が得られるはずである. 出力を見ると, Tesla T4 型の GPU が 1 台搭載されていることが確認できる. その他,GPU Driver や CUDA のバージョン, GPU の負荷・メモリー使用率などの情報を確認することができる.

nvidia-smi の出力

Jupyter Notebook の起動

Jupyter Notebook とは,インタラクティブに Python のプログラムを書いたり実行したりするためのツールである. Jupyter は GUI としてウェブブラウザを介してアクセスする形式をとっており,まるでノートを書くように,プロットやテーブルのデータも美しく表示することができる (figure_title). Python に慣れている読者は,きっと一度は使ったことがあるだろう.

Jupyter Notebook の画面

このハンズオンでは, Jupyter Notebook を使ってディープラーニングのプログラムをインタラクティブに実行していく. DLAMI には既に Jupyter がインストールされているので,特段の設定なしに使い始めることができる.

早速, Jupyter を起動しよう. SSH でログインした先の EC2 インスタンスで,次のコマンドを実行すればよい.

sh
$ cd ~ # go to home directory
$ jupyter notebook
$ cd ~ # go to home directory
$ jupyter notebook

このコマンドを実行すると, figure_title のような出力が確認できるだろう. この出力から,Jupyter のサーバーが EC2 インスタンスの localhost:8888 というアドレスに起動していることがわかる. また, localhost:8888 に続く ?token=XXXX は,アクセスに使うための一時的なトークンである.

Jupyter Notebook サーバーを起動

Jupyter Notebook を初回に起動するときは,起動に数分程度の時間がかかることがある. ほかの動作も起動直後は遅く,いくつかプログラムを走らせていくうちに俊敏に反応するようになってくる. これは, AWS の GPU 搭載型仮想マシンの運用方法に起因する現象だと考えられる.

先ほど,ポートフォワーディングのオプションをつけて SSH 接続をしているので, Jupyter の起動している localhost:8888 には,ローカルマシンの localhost:8931 からアクセスすることができる. したがって,ローカルマシンから Jupyter にアクセスするには,ウェブブラウザ (Chrome, FireFox など)から次のアドレスにアクセスすれば良い.

http://localhost:8931/?token=XXXX&lt;/programlisting&gt;

?token=XXXX の部分は,上で Jupyter を起動したときに発行されたトークンの値に置き換える.

上のアドレスにアクセスすると, Jupyter のホーム画面が起動するはずである (figure_title). これで, Jupyter の準備が整った!

Jupyter ホーム画面

Jupyter Notebook の使い方 (超簡易版)

  • Shift + Enter: セルを実行

  • Esc: Command mode に遷移

  • メニューバーの "+" ボタン または Command mode で A ⇒ セルを追加

  • メニューバーの "ハサミ" ボタン または Command mode で X ⇒ セルを削除

ショートカットの一覧などは Ventsislav Yordanov 氏によるブログ が参考になる.

PyTorch はじめの一歩

PyTorch は Facebook AI Research LAB (FAIR) が中心となって開発を進めている,オープンソースのディープラーニングのライブラリである. PyTorch は 有名な例で言えば Tesla 社の自動運転プロジェクトなどで使用されており,執筆時点において最も人気の高いディープラーニングライブラリの一つである. 本ハンズオンでは, PyTorch を使ってディープラーニングの実践を行う.

PyTorch の歴史のお話

Facebook は PyTorch のほかに Caffe2 とよばれるディープラーニングのフレームワークを開発していた (初代 Caffe は UC Berkley の博士課程学生だった Yangqing Jia によって創られた). Caffe2 は 2018 年に PyTorch プロジェクトに合併された.

また,2019 年 12 月,日本の Preferred Networks 社が開発していた Chainer も開発を終了し,PyTorch の開発チームと協業していくことが発表された (詳しくは プレスリリース を参照). PyTorch には,開発統合前から Chainer からインスパイアされた API がいくつもあり, Chainer の DNA は今も PyTorch に引き継がれているのである…!

本格的なディープラーニングの計算に移る前に, PyTorch ライブラリを使って, GPU で計算を行うとはどういうものか,その入り口に触れてみよう.

まずは,新しいノートブックを作成する. Jupyter のホーム画面の右上の "New" を押し,"conda_pytorch_p36" という環境を選択したうえで,新規ノートブックを作成する (figure_title). "conda_pytorch_p36" の仮想環境には, PyTorch がインストール済みである.

新規ノートブックの作成. "conda_pytorch_p36" の環境を選択する.

ここでは,次のようなプログラムを書いて,実行していく. (figure_title).

PyTorch始めの一歩

まずは, PyTorch をインポートする.さらに, GPU が使える環境にあるか,確認する.

python
import torch
print("Is CUDA ready?", torch.cuda.is_available())
import torch
print("Is CUDA ready?", torch.cuda.is_available())

出力:

Is CUDA ready? True</programlisting>

次に,3x3 のランダムな行列を CPU 上に作ってみよう.

python
x = torch.rand(3,3)
print(x)
x = torch.rand(3,3)
print(x)

出力:

tensor([[0.6896, 0.2428, 0.3269], [0.0533, 0.3594, 0.9499], [0.9764, 0.5881, 0.0203]])</programlisting>

次に,行列を GPU 上に作成する.

python
y = torch.ones_like(x, device="cuda")
x = x.to("cuda")
y = torch.ones_like(x, device="cuda")
x = x.to("cuda")

そして,行列 xy の加算を,GPU 上で実行する

python
z = x + y
print(z)
z = x + y
print(z)

出力:

tensor([[1.6896, 1.2428, 1.3269], [1.0533, 1.3594, 1.9499], [1.9764, 1.5881, 1.0203]], device='cuda:0')</programlisting>

最後に, GPU 上にある行列を, CPU に戻す.

python
z = z.to("cpu")
print(z)
z = z.to("cpu")
print(z)

出力:

tensor([[1.6896, 1.2428, 1.3269], [1.0533, 1.3594, 1.9499], [1.9764, 1.5881, 1.0203]])</programlisting>

以上の例は, GPU を使った計算の初歩の初歩であるが,雰囲気はつかめただろうか? CPU と GPU で明示的にデータを交換するのが肝である. この例はたった 3x3 の行列の足し算なので, GPU を使う意味はまったくないが,これが数千,数万のサイズの行列になったとき, GPU は格段の威力を発揮する.

完成した Jupyter Notebook は /handson/mnist/pytorch/pytorch_get_started.ipynb にある. Jupyter の画面右上の "Upload" からこのファイルをアップロードして,コードを走らせることが可能である.

しなしながら,勉強のときにはコードはすべて自分の手で打つことが,記憶に残りやすくより効果的である,というのが筆者の意見である.

実際にベンチマークを取ることで GPU と CPU の速度を比較をしてみよう. 実行時間を計測するツールとして, Jupyter の提供する %time マジックコマンドを利用する.

まずは CPU を使用して,10000x10000 の行列の行列積を計算した場合の速度を測ってみよう. 先ほどのノートブックの続きに,次のコードを実行する.

python
s = 10000
device = "cpu"
x = torch.rand(s, s, device=device, dtype=torch.float32)
y = torch.rand(s, s, device=device, dtype=torch.float32)

%time z = torch.matmul(x,y)
s = 10000
device = "cpu"
x = torch.rand(s, s, device=device, dtype=torch.float32)
y = torch.rand(s, s, device=device, dtype=torch.float32)

%time z = torch.matmul(x,y)

出力は以下のようなものが得られるだろう. これは,行列積の計算に実時間で 5.8 秒かかったことを意味する (実行のたびに計測される時間はばらつくことに留意).

CPU times: user 11.5 s, sys: 140 ms, total: 11.6 s Wall time: 5.8 s</programlisting>

次に, GPU を使用して,同じ演算を行った場合の速度を計測しよう.

python
s = 10000
device = "cuda"
x = torch.rand(s, s, device=device, dtype=torch.float32)
y = torch.rand(s, s, device=device, dtype=torch.float32)
torch.cuda.synchronize()

%time z = torch.matmul(x,y); torch.cuda.synchronize()
s = 10000
device = "cuda"
x = torch.rand(s, s, device=device, dtype=torch.float32)
y = torch.rand(s, s, device=device, dtype=torch.float32)
torch.cuda.synchronize()

%time z = torch.matmul(x,y); torch.cuda.synchronize()

出力は以下のようなものになるだろう. GPU では 553 ミリ秒 で計算を終えることができた!

CPU times: user 334 ms, sys: 220 ms, total: 554 ms Wall time: 553 ms</programlisting>

PyTorch において, GPU での演算は asynchronous (非同期) で実行される. その理由で,上のベンチマークコードでは, torch.cuda.synchronize() というステートメントを埋め込んである.

このベンチマークでは, dtype=torch.float32 と指定することで,32bit の浮動小数点型を用いている. ディープラーニングの学習および推論の計算には,32bit 型,場合によっては 16bit 型が使われるのが一般的である. これの主な理由として,教師データやミニバッチに起因するノイズが,浮動小数点の精度よりも大きいことがあげられる. 32bit/16bit を採用することで,メモリー消費を抑えたり,計算速度の向上が達成できる.

上記のベンチマークから,GPU を用いることで,約 10 倍のスピードアップを実現することができた. スピードアップの性能は,演算の種類や行列のサイズに依存する. 行列積は,そのなかでも最も速度向上が見込まれる演算の一つである.

実践ディープラーニング! MNIST 手書き数字認識タスク

ここまで,AWS 上でディープラーニングの計算をするための概念や前提知識をながながと説明してきたが,ついにここからディープラーニングの計算を実際に走らせてみる.

ここでは,機械学習のタスクで最も初歩的かつ有名な MNIST データセットを使った数字認識を扱う (figure_title). これは,0 から 9 までの手書きの数字の画像が与えられ,その数字が何の数字なのかを当てる,というシンプルなタスクである.

MNIST 手書き数字データセット

今回は, MNIST 文字認識タスクを,畳み込みニューラルネットワーク (Convolutional Neural Network; CNN) を使って解く. ソースコードは /handson/minist/pytorch/ にある mnist.ipynbsimple_mnist.py である. なお,このプログラムは, PyTorch の公式 Example Project 集 を参考に,多少の改変を行ったものである.

まずは,カスタムのクラスや関数が定義された simple_mnist.py をアップロードしよう (figure_title). 画面右上の "Upload" ボタンをクリックし,ファイルを選択することでアップロードができる. この Python プログラムの中に,CNN のモデルや,学習の各イテレーションにおけるパラメータの更新などが記述されている. 今回はこの中身を説明することはしないが,興味のある読者は自身でソースコードを読んでみるとよい.

 をアップロード

simple_mnist.py をアップロードできたら,次に新しい notebook を作成しよう. "conda_pytorch_p36" の環境を選択することを忘れずに.

新しいノートブックが起動したら,まずは必要なライブラリをインポートしよう.

python
import torch
import torch.optim as optim
import torchvision
from torchvision import datasets, transforms
from matplotlib import pyplot as plt

# custom functions and classes
from simple_mnist import Model, train, evaluate
import torch
import torch.optim as optim
import torchvision
from torchvision import datasets, transforms
from matplotlib import pyplot as plt

# custom functions and classes
from simple_mnist import Model, train, evaluate

torchvision パッケージには,MNIST データセットをロードするなどの便利な関数が含まれている. また,今回のハンズオンで使うカスタムのクラス・関数 (Model, train, evaluate) のインポートを行っている.

次に,MNIST テストデータをダウンロードしよう. 同時に,画像データの輝度の正規化も行っている.

python
transf = transforms.Compose([transforms.ToTensor(),
                             transforms.Normalize((0.1307,), (0.3081,))])

trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transf)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)

testset = datasets.MNIST(root='./data', train=False, download=True, transform=transf)
testloader = torch.utils.data.DataLoader(testset, batch_size=1000, shuffle=True)
transf = transforms.Compose([transforms.ToTensor(),
                             transforms.Normalize((0.1307,), (0.3081,))])

trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transf)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)

testset = datasets.MNIST(root='./data', train=False, download=True, transform=transf)
testloader = torch.utils.data.DataLoader(testset, batch_size=1000, shuffle=True)

今回扱う MNIST データは 28x28 ピクセルの正方形の画像(モノクロ)と,それぞれのラベル(0 - 9 の数字)の組で構成されている. いくつかのデータを抽出して,可視化してみよう. figure_title のような出力が得られるはずである.

python
examples = iter(testloader)
example_data, example_targets = examples.next()

print("Example data size:", example_data.shape)

fig = plt.figure(figsize=(10,4))
for i in range(10):
    plt.subplot(2,5,i+1)
    plt.tight_layout()
    plt.imshow(example_data[i][0], cmap='gray', interpolation='none')
    plt.title("Ground Truth: {}".format(example_targets[i]))
    plt.xticks([])
    plt.yticks([])
plt.show()
examples = iter(testloader)
example_data, example_targets = examples.next()

print("Example data size:", example_data.shape)

fig = plt.figure(figsize=(10,4))
for i in range(10):
    plt.subplot(2,5,i+1)
    plt.tight_layout()
    plt.imshow(example_data[i][0], cmap='gray', interpolation='none')
    plt.title("Ground Truth: {}".format(example_targets[i]))
    plt.xticks([])
    plt.yticks([])
plt.show()

MNIST の手書き数字画像とその教師ラベル

次に, CNN のモデルを定義する.

python
model = Model()
model.to("cuda") # load to GPU
model = Model()
model.to("cuda") # load to GPU

今回使う Modelsimple_mnist.py の中で定義されている. このモデルは,figure_title に示したような,2層の畳み込み層と 2 層の全結合層からなるネットワークである. 出力層 (output layer) には Softmax 関数を使用し,損失関数 (Loss function) には 負の対数尤度関数 (Negative log likelyhood; NLL) を使用している.

本ハンズオンで使用するニューラルネットの構造.

続いて, CNN のパラメータを更新する最適化アルゴリズムを定義する. ここでは, 確率的勾配降下法 (Stochastic Gradient Descent; SGD) を使用している.

python
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)

これで,準備が整った. CNN の学習ループを開始しよう!

python
train_losses = []
for epoch in range(5):
    losses = train(model, trainloader, optimizer, epoch)
    train_losses = train_losses + losses
    test_loss, test_accuracy = evaluate(model, testloader)
    print(f"\nTest set: Average loss: {test_loss:.4f}, Accuracy: {test_accuracy:.1f}%\n")

plt.figure(figsize=(7,5))
plt.plot(train_losses)
plt.xlabel("Iterations")
plt.ylabel("Train loss")
plt.show()
train_losses = []
for epoch in range(5):
    losses = train(model, trainloader, optimizer, epoch)
    train_losses = train_losses + losses
    test_loss, test_accuracy = evaluate(model, testloader)
    print(f"\nTest set: Average loss: {test_loss:.4f}, Accuracy: {test_accuracy:.1f}%\n")

plt.figure(figsize=(7,5))
plt.plot(train_losses)
plt.xlabel("Iterations")
plt.ylabel("Train loss")
plt.show()

ここでは 5 エポック分の学習を行っている. GPU を使えば,これくらいの計算であれば 1 分程度で完了するだろう.

出力として, figure_title のようなプロットが得られるはずである. イテレーションを重ねるにつれて,損失関数 (Loss function) の値が減少している (=精度が向上している) ことがわかる.

学習の進行に対する Train loss の変化

出力にはテキスト形式で各エポック終了後のテストデータに対する精度も表示されている. 最終的には 98% 以上の極めて高い精度を実現できていることが確認できるだろう (figure_title).

学習したCNNのテストデータに対するスコア (5エポック後)

学習した CNN の推論結果を可視化してみよう. 次のコードを実行することで, figure_title のような出力が得られるだろう. この図で,下段右から二番目は,"1"に近い見た目をしているが,きちんと"9"と推論できている. なかなか賢い CNN を作り出すことができたようだ!

python
model.eval()

with torch.no_grad():
    output = model(example_data.to("cuda"))

fig = plt.figure(figsize=(10,4))
for i in range(10):
    plt.subplot(2,5,i+1)
    plt.tight_layout()
    plt.imshow(example_data[i][0], cmap='gray', interpolation='none')
    plt.title("Prediction: {}".format(output.data.max(1, keepdim=True)[1][i].item()))
    plt.xticks([])
    plt.yticks([])
plt.show()
model.eval()

with torch.no_grad():
    output = model(example_data.to("cuda"))

fig = plt.figure(figsize=(10,4))
for i in range(10):
    plt.subplot(2,5,i+1)
    plt.tight_layout()
    plt.imshow(example_data[i][0], cmap='gray', interpolation='none')
    plt.title("Prediction: {}".format(output.data.max(1, keepdim=True)[1][i].item()))
    plt.xticks([])
    plt.yticks([])
plt.show()

学習した CNN による,MNIST画像の推論結果

最後に,学習したニューラルネットワークのパラメータを mnist_cnn.pt というファイル名で保存しておこう. これで,将来いつでも今回学習したモデルを再現し,別の実験に使用することができる.

python
torch.save(model.state_dict(), "mnist_cnn.pt")
torch.save(model.state_dict(), "mnist_cnn.pt")

以上が, AWS クラウドの仮想サーバーを立ち上げ,最初のディープラーニングの計算を行う一連の流れである. MNIST 文字認識のタスクを行うニューラルネットを,クラウド上の GPU を使って高速に学習させ,現実的な問題を一つ解くことができたのである. 興味のある読者は,今回のハンズオンを雛形に,自分の所望の計算を走らせてみるとよいだろう.

スタックの削除

これにて,ハンズオン第二回の内容はすべて説明した. クラウドの利用料金を最小化するため,使い終わった EC2 インスタンスはすぐさま削除しよう.

ハンズオン第一回と同様に, AWS の CloudFormation コンソールか, AWS CLI により削除を実行する (詳細は スタックを削除 参照).

sh
$ cdk destroy
$ cdk destroy

スタックの削除は各自で必ず行うこと! 行わなかった場合,EC2 インスタンスの料金が発生し続けることになる! g4dn.xlarge は $0.71 / hour の料金設定なので,一日起動しつづけると約$17 の請求が発生することになる!

AWS のバジェットアラート

AWS の初心者が (あるいは経験者も) しばしば陥る失敗が,インスタンスの停止忘れなどで無駄なリソースがクラウドで放置されてしまい,巨大な額の請求が届く,というミスだ. 特に,開発を行っている間はこのような事態は起こりうるものだと思って,備えておかなければならない. このような事態を未然に防ぐため, AWS Budgets という機能が無料で提供されている. AWS Budgets を利用することで,月の利用金額がある閾値を超えた場合にユーザーにメールが送信される,などのアラートを設定することができる. 詳細な手順は AWS の公式ブログ "Getting Started with AWS Budgets" を参照のこと. 本書の読者も,ぜひこのタイミングでアラートを設定しておくことを推奨する.

Docker 入門

ここまでの章で扱ってきたハンズオンでは,単一のサーバーを立ち上げ,それに SSH でログインをして,コマンドを叩くことで計算を行ってきた. いわば,パーソナルコンピュータの延長のような形でクラウドを使ってきたわけである. このような,インターネットのどこからでもアクセスできるパーソナルコンピュータとしてのクラウドという使い方も,もちろん便利であるし,いろいろな応用の可能性がある. しかし,これだけではクラウドの本当の価値は十分に発揮されていないと言うべきだろう. クラウド概論 で述べたように,現代的なクラウドの一番の強みは自由に計算機の規模を拡大できることにある. すなわち,多数のサーバーを同時に起動し,複数のジョブを分散並列的に実行させることで大量のデータを処理してこそ,クラウドの本領が発揮されるのである.

本章からはじまる 3 章分 (Docker 入門, Hands-on #3: AWS で自動質問回答ボットを走らせる, Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する) を使って,クラウドを利用することでどのように大規模な計算システムを構築しビッグデータの解析に立ち向かうのか,その片鱗をお見せしたい. とくに,前章で扱った深層学習をどのようにビッグデータに適用していくかという点に焦点を絞って議論していきたい. そのための前準備として,本章では Docker とよばれる計算機環境の仮想化ソフトウェアを紹介する (figure_title). 現代のクラウドは Docker なしには成り立たないといっても過言ではないだろう. クラウドに限らず,ローカルで行う計算処理にも Docker は大変便利である. AWS からは少し話が離れるが,しっかりと理解して前に進んでもらいたい.

機械学習の大規模化

先ほどから"計算システムの大規模化"と繰り返し唱えているが,それは具体的にはどのようなものを指しているのか? ここでは大規模データを処理するための計算機システムを,機械学習を例にとって見てみよう.

クラウドで行う科学計算・機械学習 で紹介した GPT-3 のような,超巨大な数のパラメータを有する深層学習モデルを学習させたいとしよう. そのような計算を行いたい場合,一つのサーバーでは計算力が到底足りない. したがって,典型的には figure_title に示すような計算システムの設計がなされる. すなわち,大量の教師データを小さなチャンクとして複数のマシンに分散し,並列的にニューラルネットのパラメータを最適化していくという構造である.

複数の計算機を使った大規模な深層学習モデルの訓練

あるいは,学習済みのモデルを大量のデータに適用し,解析を行いたいとしよう. たとえば, SNS のプラットフォームで大量の画像が与えられて,それぞれの写真に何が写っているのかをラベルづけする,などのアプリケーションを想定できる. そのような場合は, figure_title のようなアーキテクチャが考えられるだろう. すなわち,大量のデータを複数のマシンで分割し,それぞれのマシンで推論の計算を行うというような構造である.

複数の計算機による深層学習モデルを使った推論計算

このような複数の計算機を同時に走らせるようなアプリケーションをクラウド上で実現するには,どのようにすればよいのだろうか?

重要なポイントとして, figure_titlefigure_title で起動している複数のマシンは,基本的に全く同一の OS・計算環境を有している点である. ここで,個人のコンピュータで行うようなインストールの操作を,各マシンで行うこともできるが,それは大変な手間であるし,メンテナンスも面倒だろう. すなわち,大規模な計算システムを構築するには,簡単に計算環境を複製できるような仕組みが必要であるということがわかる.

そのような目的を実現するために使われるのが, Docker とよばれるソフトウェアである.

Docker とは

Docker のアイコン

Docker とは, コンテナ (Container) とよばれる仮想環境下で,ホスト OS とは独立した別の計算環境を走らせるためのソフトウェアである. Docker を使うことで, OS を含めたすべてのプログラムをコンパクトにパッケージングすることが可能になる (パッケージされた一つの計算環境のことを **イメージ (Image)**とよぶ). Docker を使うことで,クラウドのサーバー上に瞬時に計算環境を複製することが可能になり, figure_title で見たような複数の計算機を同時に走らせるためのシステムが実現できる.

Docker は 2013 年に Solomon Hykes らを中心に開発され,それ以降爆発的に普及し,クラウドコンピューティングだけでなく,機械学習・科学計算の文脈などでも欠かすことのできないソフトウェアとなった. Docker はエンタープライズ向けの製品を除き無料で使用することができ,コアの部分は オープンソースプロジェクト として公開されている. Docker は Linux, Windows, Mac いずれの OS でも提供されている. 概念としては, Docker は仮想マシン (Virtual machine; VM) にとても近い. ここでは, VM との対比をしながら,Docker とはなにかを簡単に説明しよう.

仮想マシン (VM) とは,ホストとなるマシンの上に,仮想化された OS を走らせる技術である (figure_title). VM には ハイパーバイザー (Hypervisor) とよばれるレイヤーが存在する. Hypervisor はまず,物理的な計算機リソース (CPU, RAM, network など) を分割し,仮想化する. たとえば, ホストマシンに物理的な CPU が 4 コアあるとして,ハイパーバイザーはそれを (2,2) 個の組に仮想的に分割することができる. VM 上で起動する OS には,ハイパーバイザーによって仮想化されたハードウェアが割り当てられる. VM 上で起動する OS は基本的に完全に独立であり,たとえば OS-A は OS-B に割り当てられた CPU やメモリー領域にアクセスすることはできない (これを isolation とよぶ). VM を作成するための有名なソフトウェアとしては, VMwareVirtualBoxXen などがある. また,これまで触ってきた EC2 も,基本的に VM 技術を使うことで所望のスペックをもった仮想マシンがユーザーに提示される.

Docker も, VM と同様に,仮想化された OS をホストの OS 上に走らせるための技術である. VM に対し, Docker ではハードウェアレベルの仮想化は行われておらず,すべての仮想化はソフトウェアレベルで実現されている (figure_title). Docker で走る仮想 OS は,多くの部分をホストの OS に依存しており,結果として非常にコンパクトである. その結果, Docker で仮想 OS を起動するために要する時間は, VM に比べて圧倒的に早い. また, パッケージ化された環境 (=イメージ) のサイズも完全な OS に比べ圧倒的に小さくなるので,ネットワークを通じたやり取りが非常に高速化される点も重要である 加えて, VM のいくつかの実装では,メタル (仮想化マシンに対して,物理的なハードウェア上で直接起動する場合のこと) と比べ,ハイパーバイザーレイヤーでのオーバーヘッドなどにより性能が低下することが知られているが, Docker ではメタルとほぼ同様の性能を引き出すことができるとされている.

その他, VM との相違点などはたくさんあるのだが,ここではこれ以上詳細には立ち入らない. 大事なのは, Docker とはとてもコンパクトかつハイパフォーマンスな仮想計算環境を作るツールである,という点である. その手軽さゆえに,2013 年の登場以降,クラウドシステムでの利用が急速に増加し,現代のクラウドでは欠くことのできない中心的な技術になっている.

Docker (左) と VM (右) の比較 (画像出典: https://www.docker.com/blog/containers-replacing-virtual-machines/)

職業的プログラマーにとっての"三種の神器"とはなんだろうか? 多様な意見があると思うが,筆者は Git, Vim そして Docker を挙げたい.

Git は多くの読者がご存じの通り,コードの変更を追跡するためのシステムである. Linux の作成者である Linus Torvalds によって 2005 年に誕生した. チームでの開発を進める際には欠かせないツールだ.

Vim は 1991 年から 30 年以上の間プログラマーたちに愛されてきたテキストエディターである. Stackoverflow が行った 2019 年のアンケート によると,開発環境の部門で 5 位の人気を獲得している. たくさんのショートカットと様々なカスタム設定が提供されているので,初見の人にはなかなかハードルが高いが,一度マスターすれば他のモダンなエディターや統合開発環境に負けない,あるいはそれ以上の開発体験を実現することができる.

これらの十年以上の歴史あるツールに並んで,第三番目の三種の神器として挙げたいのが Docker だ. Docker はプログラマーの開発のワークフローを一変させた. たとえば,プロジェクトごとに Docker イメージを作成することで,どの OS・コンピュータ でも全く同じ計算環境で開発・テストを実行することができるようになった. また, DevOpsCI / CD (Continuous Integration / Continuous Deployment) といった最近の開発ワークフローも Docker のようなコンテナ技術の存在に立脚している. さらにはサーバーレスコンピューティング (Serverless architecture) といった概念も,コンテナ技術の生んだ大きな技術革新といえる.

あなたにとっての三種の神器はなんだろうか? また,これからの未来ではどんな新しいツールが三種の神器としてプログラマーのワークフローを革新していくだろうか?

Docker チュートリアル

Docker とはなにかを理解するためには,実際に触って動かしてみるのが一番有効な手立てである. ここでは, Docker の簡単なチュートリアルを行っていく.

Docker のインストールについては, Docker のインストール および 公式のドキュメンテーション を参照してもらいたい. Docker のインストールが完了している前提で,以下は話を進めるものとする.

Docker 用語集

Docker を使い始めるに当たり,最初に主要な用語を解説しよう. 次のパラグラフで太字で強調された用語を頭に入れた上で,続くチュートリアルに取り組んでいただきたい.

Docker を起動する際の大まかなステップを示したのが figure_title である. パッケージされた一つの計算環境のことを **イメージ (Image)**とよぶ. イメージは, Docker Hub などのリポジトリで配布されているものをダウンロードするか,自分でカスタムのイメージを作成することも可能である. イメージを作成するための”レシピ”を記述したファイルが Dockerfile である. Dockerfile からイメージを作成する操作を build とよぶ. イメージがホストマシンのメモリにロードされ,起動状態にある計算環境のことを コンテナ (Container) とよぶ. Container を起動するために使用されるコマンドが run である.

Image と Container

イメージをダウンロード

パッケージ化された Docker の仮想環境 (= イメージ (Image)) は, Docker Hub からダウンロードできる. Docker Hub には,個人や企業・団体が作成した Docker イメージが集められており, GitHub などと同じ感覚で,オープンな形で公開されている.

たとえば, Ubuntu のイメージは Ubuntu の公式リポジトリ で公開されており, pull コマンドを使うことでローカルにダウンロードすることができる.

sh
$ docker pull ubuntu:18.04
$ docker pull ubuntu:18.04

ここで,イメージ名の : (コロン) 以降に続く文字列を タグ (tag) と呼び,主にバージョンを指定するなどの目的で使われる.

pull コマンドはデフォルトでは Docker Hub でイメージを検索し,ダウンロードを行う. Docker イメージを公開するためのデータベース (レジストリ (registry) とよぶ) は Docker Hub だけではなく,たとえば GitLab や GitHub は独自のレジストリ機能を提供しているし,個人のサーバーでレジストリを立ち上げることも可能である. Docker Hub 以外のレジストリから pull するには, myregistry.local:5000/testing/test-image のように,イメージ名の先頭につける形でレジストリのアドレス (さらにオプションとしてポート番号) を指定する.

コンテナを起動

Pull してきたイメージを起動するには, run コマンドを使う.

sh
$ docker run -it ubuntu:18.04
$ docker run -it ubuntu:18.04

ここで, -it とは,インタラクティブな shell のセッションを開始するために必要なオプションである.

このコマンドを実行すると,仮想化された Ubuntu が起動され,コマンドラインからコマンドが打ち込めるようになる (figure_title). このように起動状態にある計算環境 (ランタイム) のことを Container (コンテナ) とよぶ.

Docker を使って ubuntu:18.04 イメージを起動

ここで使用した ubuntu:18.04 のイメージは,空の Ubuntu OS だが,すでにプログラムがインストール済みのものもある. これは, Hands-on #2: AWS でディープラーニングを実践 でみた DLAMI と概念として似ている. たとえば, PyTorch がインストール済みのイメージは PyTorch 公式の Docker Hub リポジトリ で公開されている.

これを起動してみよう.

sh
$ docker run -it pytorch/pytorch
$ docker run -it pytorch/pytorch

docker run を実行したとき,ローカルに該当するイメージが見つからない場合は,自動的に Docker Hub からダウンロードされる.

pytorch のコンテナが起動したら, Python のシェルを立ち上げて, pytorch をインポートしてみよう.

sh
$ python3
Python 3.7.7 (default, May  7 2020, 21:25:33)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.cuda.is_available()
False
$ python3
Python 3.7.7 (default, May  7 2020, 21:25:33)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.cuda.is_available()
False

このように, Docker を使うことで簡単に特定の OS・プログラムの入った計算環境を再現することが可能になる.

自分だけのイメージを作る

自分の使うソフトウェア・ライブラリがインストールされた,自分だけのイメージを作ることも可能である.

たとえば, 本書のハンズオン実行用に提供している docker イメージ には, Python, Node.js, AWS CLI, AWS CDK などのソフトウェアがインストール済みであり,ダウンロードしてくるだけですぐにハンズオンのプログラムが実行できるようになっている.

カスタムの docker イメージを作るには, Dockerfile という名前のついたファイルを用意し,その中にどんなプログラムをインストールするかなどを記述していく.

具体例として,本書で提供している Docker イメージのレシピを見てみよう (docker/Dockerfile).

python
FROM node:12
LABEL maintainer="Tomoyuki Mano"

RUN apt-get update \
    && apt-get install nano

#
RUN cd /opt \
    && curl -q "https://www.python.org/ftp/python/3.7.6/Python-3.7.6.tgz" -o Python-3.7.6.tgz \
    && tar -xzf Python-3.7.6.tgz \
    && cd Python-3.7.6 \
    && ./configure --enable-optimizations \
    && make install

RUN cd /opt \
    && curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" \
    && unzip awscliv2.zip \
    && ./aws/install

#
RUN npm install -g aws-cdk@1.100

# clean up unnecessary files
RUN rm -rf /opt/*

# copy hands-on source code in /root/
COPY handson/ /root/handson
FROM node:12
LABEL maintainer="Tomoyuki Mano"

RUN apt-get update \
    && apt-get install nano

#
RUN cd /opt \
    && curl -q "https://www.python.org/ftp/python/3.7.6/Python-3.7.6.tgz" -o Python-3.7.6.tgz \
    && tar -xzf Python-3.7.6.tgz \
    && cd Python-3.7.6 \
    && ./configure --enable-optimizations \
    && make install

RUN cd /opt \
    && curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" \
    && unzip awscliv2.zip \
    && ./aws/install

#
RUN npm install -g aws-cdk@1.100

# clean up unnecessary files
RUN rm -rf /opt/*

# copy hands-on source code in /root/
COPY handson/ /root/handson

Dockerfile の中身の説明は詳しくは行わないが,たとえば上のコードで <1> で示したところは, Python 3.7 のインストールを実行している. また, <2> で示したところは, AWS CDK のインストールを行っていることがわかるだろう. このように,リアルな OS で行うのと同じ流れでインストールのコマンドを逐一記述していくことで,自分だけの Docker イメージを作成することができる. 一度イメージを作成すれば,それを配布することで,他者も同一の計算環境を簡単に再構成することができる.

"ぼくの環境ではそのプログラム走ったのにな…" というのは,プログラミング初心者ではよく耳にする会話だが, Docker を使いこなせばそのような心配とは無縁である. そのような意味で,クラウド以外の場面でも, Docker の有用性・汎用性は極めて高い.

コンテナを用いた仮想計算環境ツールとして Docker を紹介したが, ほかに選択肢はないのか? よくぞ聞いてくれた! Docker の登場以降,複数のコンテナベースの仮想環境ツールが開発されてきた. いずれのツールも,概念や API については Docker と共通するものが多いが,Docker にはない独自の特徴を提供している. ここではその中でも有名ないくつかを紹介しよう.

Singularity は科学計算や HPC (High Performance Computing) の分野で人気の高いコンテナプラットフォームである. Singularity では大学・研究機関の HPC クラスターでの運用に適したような設計が施されている. たとえば, Docker は基本的には root 権限で実行されるのに対し, Singularity はユーザー権限 (コマンドを実行したユーザー自身) でプログラムが実行される. root 権限での実行は Web サーバーのように個人・企業がある特定のサービスのために運用するサーバーでは問題ないが,多数のユーザーが多様な目的で計算を実行する HPC クラスターでは問題となる. また,Singularity は独自のイメージの作成方法・エコシステムをもっているが, Docker イメージを Singularity のイメージに変換し実行する機能も有している.

podman は Red Hat 社によって開発されたもう一つのコンテナプラットフォームである. podman は基本的に Docker と同一のコマンドを採用しているが,実装は Red Hat によってスクラッチから行われた. podman では, Singularity と同様にユーザー権限でのプログラムの実行を可能であり,クラウドおよび HPC の両方の環境に対応するコンテナプラットフォームを目指して作られた. また,その名前にあるとおり pod とよばれる独自の概念が導入されている.

著者の個人的な意見としては,現時点では Docker をマスターしておけば当面は困ることはないと考えるが,興味のある読者はぜひこれらのツールも試してみてはいかがだろうか?

Elastic Container Service (ECS)

ECS のアイコン

ここまでに説明してきたように, Docker を使うことで仮想計算環境を簡単に複製・起動することが可能になる. 本章の最後の話題として, AWS 上で Docker を使った計算システムを構築する方法を解説しよう.

Elastic Container Service (ECS) とは, Docker を使った計算機クラスターを AWS 上に作成するためのツールである (figure_title). ECS を使用することで, Docker にパッケージされたアプリケーションを計算機クラスターに投入したり,計算機クラスターのインスタンスを追加・削除する操作 (=スケーリング) を行うことができる.

ECS の概要を示したのが figure_title である. ECS は,タスク (Task) と呼ばれる単位で管理された計算ジョブを受け付ける. システムにタスクが投入されると,ECS は最初にタスクで指定された Docker イメージを外部レジストリからダウンロードしてくる. 外部レジストリとしては, Docker Hub や AWS 独自の Docker レジストリである ECR (Elastic Container Registry) を指定することができる.

ECS の次の重要な役割はタスクの配置である. あらかじめ定義されたクラスター内で,計算負荷が小さい仮想インスタンスを選び出し,そこに Docker イメージを配置することで指定された計算タスクが開始される. "計算負荷が小さい仮想インスタンスを選び出す" と言ったが,具体的にどのような戦略・ポリシーでこの選択を行うかは,ユーザーの指定したパラメータに従う.

また,クラスターのスケーリングも ECS における重要な概念である. スケーリングとは,クラスター内のインスタンスの計算負荷をモニタリングし,計算負荷に応じてインスタンスの起動・停止を行う操作を指す. クラスター全体の計算負荷が指定された閾値 (たとえば 80%の稼働率) を超えていた場合,新たな仮想インスタンスをクラスター内に立ち上げる操作を scale-out (スケールアウト) とよび, 負荷が減った場合に不要なインスタンスを停止する操作を scale-in (スケールイン) とよぶ. クラスターのスケーリングは, ECS がほかの AWS のサービスと連携することで実現される. 具体的には, EC2 の Auto scaling group (ASG)Fargate の2つの選択肢が多くの場合選択される. ASG については Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する, Fargate については Hands-on #3: AWS で自動質問回答ボットを走らせる でより詳細に解説する.

これら一連のタスクの管理を, ECS は自動でやってくれる. クラスターのスケーリングやタスクの配置に関してのパラメータを一度指定してしまえば,ユーザーは (ほとんどなにも考えずに) 大量のタスクを投入することができる. クラスターのスケーリングによってタスクの量にちょうど十分なだけのインスタンスが起動し,タスクが完了した後は不要なインスタンスはすべて停止される.

さて,ここまで説明的な話が続いてしまったが,次章からは早速 Docker と AWS を使って大規模な並列計算システムを構築していこう!

ECS の概要

Hands-on #3: AWS で自動質問回答ボットを走らせる

ハンズオン第三回では, Docker と ECS を駆使した機械学習アプリケーションを実装しよう. 具体的には,深層学習による自然言語処理を行うことで,クライアントから与えられた文章題に対して回答を生成する,自動 Question & Answering ボットを作成しよう. ECS を利用することで,ジョブの数によって動的にインスタンスの数を制御し,並列にタスクを実行するようなシステムを構築しよう.

通常の機械学習のワークフローでは,モデルの訓練 ⇒ 推論 (データへの適用) が基本的な流れである. しかしながら, GPU 搭載型の EC2 クラスターを使ったモデルの訓練はやや難易度が高いため,次章 (Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する) で取り扱う. 本章は,クラウド上でのクラスターの構築・タスクの管理などの概念に慣れるため,よりシンプルな実装で実現できる Fargate クラスターを用いた推論計算の並列化を紹介する.

Fargate

ハンズオンに入っていく前に, Fargate という AWS の機能を知っておく必要がある (figure_title).

Fargate のアイコン

ECS の概要を示した figure_title をもう一度見てみよう. この図で, ECS の管理下にあるクラスターが示されているが,このクラスターの中で計算を行う実体としては二つの選択肢がある. EC2 あるいは Fargate のいずれかである. EC2 を用いた場合は,先の章 (Hands-on #1: 初めての EC2 インスタンスを起動する, Hands-on #2: AWS でディープラーニングを実践) で説明したような流れでインスタンスが起動し,計算が実行される. しかし, EC2 を用いた計算機クラスターの作成・管理は技術的な難易度がやや高いので,次章 (Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する) で説明することにする.

Fargate とは, ECS での利用に特化して設計された,コンテナを使用した計算タスクを走らせるための仕組みである. 計算を走らせるという点では EC2 と役割は似ているが, Fargate は EC2 インスタンスのような物理的実体はもたない. 物理的実体をもたないというのは,たとえば SSH でログインすることは基本的に想定されていないし,なにかのソフトウェアをインストールしたりなどの概念も存在しない. Fargate ではすべての計算は Docker コンテナを介して行われる. すなわち, Fargate を利用するには,ユーザーは最初に所望の Docker イメージを指定しておき, Fargate は docker run のコマンドを使用することで計算タスクを実行する. Fargate を用いる利点は, Fargate を ECS のクラスターに指定すると,スケーリングなどの操作が簡単な設定・プログラムで構築できる点である.

Fargate では, EC2 と同様に CPU とメモリーのサイズを必要な分だけ指定できる. 執筆時点では, CPU は 0.25 - 4 コア, RAM は 0.5 - 30 GB の間で選択することができる (詳しくは 公式ドキュメンテーション "Amazon ECS on AWS Fargate" 参照). クラスターのスケーリングが容易な分, Fargate では EC2 ほど大きな CPU コア・ RAM 容量を単一インスタンスに付与することができず,また GPU を利用することもできない.

以上が Fargate の概要であったが,くどくど言葉で説明してもなかなかピンとこないだろう. ここからは実際に手を動かしながら, ECS と Fargate を使った並列タスクの処理の仕方を学んでいこう.

厳密には, ECS に付与するクラスターには EC2 と Fargate のハイブリッドを使用することも可能である.

準備

ハンズオンのソースコードは GitHub の handson/qa-bot にある.

本ハンズオンの実行には,第一回ハンズオンで説明した準備 (準備) が整っていることを前提とする. また, Docker が自身のローカルマシンにインストール済みであることも必要である.

このハンズオンでは 1CPU/4GB RAM の Fargate インスタンスを使用する. 計算の実行には 0.025 $/hour のコストが発生することに注意.

Transformer を用いた question-answering プログラム

このハンズオンで開発する,自動質問回答システムをより具体的に定義しよう. 次のような文脈 (context) と質問 (question) が与えられた状況を想定する.

txt
context: Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist who developed the theory of relativity, one of the two pillars of modern physics (alongside quantum mechanics). His work is also known for its influence on the philosophy of science. He is best known to the general public for his mass–energy equivalence formula E = mc2, which has been dubbed \"the world's most famous equation\". He received the 1921 Nobel Prize in Physics \"for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect\", a pivotal step in the development of quantum theory.

question: In what year did Einstein win the Nobel prize?
context: Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist who developed the theory of relativity, one of the two pillars of modern physics (alongside quantum mechanics). His work is also known for its influence on the philosophy of science. He is best known to the general public for his mass–energy equivalence formula E = mc2, which has been dubbed \"the world's most famous equation\". He received the 1921 Nobel Prize in Physics \"for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect\", a pivotal step in the development of quantum theory.

question: In what year did Einstein win the Nobel prize?

今回作成する自動回答システムは,このような問題に対して, context に含まれる文字列から正解となる言葉を見つけ出すものとする. 上の問題では,次のような回答を返すべきである.

sh
answer: 1921
answer: 1921

人間にとっては,このような文章を理解することは容易であるが,コンピュータにそれを解かせるのは難しいことは容易に想像ができるだろう. しかし,近年の深層学習を使った自然言語処理の進歩は著しく,上で示したような例題などは極めて高い正答率で回答できるモデルを作ることができる.

今回は, huggingface/transformers で公開されている学習済みの言語モデルを利用することで,上で定義した問題を解く Q&A ボットを作る. この Q&A ボットは Transformer とよばれるモデルを使った自然言語処理に支えられえている (figure_title). このプログラムを, Docker にパッケージしたものが 著者の Docker Hub リポジトリ に用意してある. クラウドの設計に入る前に,まずはこのプログラムを単体で動かしてみよう.

Transformer モデルアーキテクチャ (画像出典: Vaswani+ 2017)

なお,今回は学習済みのモデルを用いているので,私達が行うのは与えられた入力をモデルに投入して予測を行う (推論) のみである. 推論の演算は, CPU だけでも十分高速に行うことができるので,コストの削減と,実装をシンプルにする目的で,このハンズオンでは GPU は利用しない. 一般的に, ニューラルネットは学習のほうが圧倒的に計算コストが大きく,そのような場合に GPU はより威力を発揮する.

次のコマンドで,今回使う Docker image を ローカルにダウンロード (pull) してこよう.

sh
$ docker pull tomomano/qabot:latest
$ docker pull tomomano/qabot:latest

pull できたら,早速この Docker に質問を投げかけてみよう. まずは context と question をコマンドラインの変数として定義する.

sh
$ context="Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist who developed the theory of relativity, one of the two pillars of modern physics (alongside quantum mechanics). His work is also known for its influence on the philosophy of science. He is best known to the general public for his mass–energy equivalence formula E = mc2, which has been dubbed the world's most famous equation. He received the 1921 Nobel Prize in Physics for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect, a pivotal step in the development of quantum theory."
$ question="In what year did Einstein win the Nobel prize ?"
$ context="Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist who developed the theory of relativity, one of the two pillars of modern physics (alongside quantum mechanics). His work is also known for its influence on the philosophy of science. He is best known to the general public for his mass–energy equivalence formula E = mc2, which has been dubbed the world's most famous equation. He received the 1921 Nobel Prize in Physics for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect, a pivotal step in the development of quantum theory."
$ question="In what year did Einstein win the Nobel prize ?"

そうしたら,次のコマンドによってコンテナを実行する.

sh
$ docker run tomomano/qabot "${context}" "${question}" foo --no_save
$ docker run tomomano/qabot "${context}" "${question}" foo --no_save

今回用意した Docker image は,第一引数に context となる文字列を,第二引数に question に相当する文字列を受けつける. 第三引数,第四引数については,クラウドに展開するときの実装上の都合なので,いまは気にしなくてよい.

このコマンドを実行すると,次のような出力が得られるはずである.

sh
{'score': 0.9881729286683587, 'start': 437, 'end': 441, 'answer': '1921'}
{'score': 0.9881729286683587, 'start': 437, 'end': 441, 'answer': '1921'}

"score" は正解の自信度を表す数字で, [0,1] の範囲で与えられる. "start", "end" は, context 中の何文字目が正解に相当するかを示しており, "answer" が正解と予測された文字列である. 1921 年という,正しい答えが返ってきていることに注目してほしい.

もう少し難しい質問を投げかけてみよう.

sh
$ question="Why did Einstein win the Nobel prize ?"
$ docker run tomomano/qabot "${context}" "${question}" foo --no_save
$ question="Why did Einstein win the Nobel prize ?"
$ docker run tomomano/qabot "${context}" "${question}" foo --no_save

出力:

sh
{'score': 0.5235594527494207, 'start': 470, 'end': 506, 'answer': 'his services to theoretical physics,'}
{'score': 0.5235594527494207, 'start': 470, 'end': 506, 'answer': 'his services to theoretical physics,'}

今度は, score が 0.52 と,少し自信がないようだが,それでも正しい答えにたどりつけていることがわかる.

このように, 深層学習に支えられた言語モデルを用いることで,実用にも役に立ちそうな Q&A ボットを実現できていることがわかる. 以降では,このプログラムをクラウドに展開することで,大量の質問に自動で対応できるようなシステムを設計していく.

今回使用する Question & Answering システムには, DistilBERT という Transformer を基にした言語モデルが用いられている. 興味のある読者は, 原著論文 を参照してもらいたい. また, huggingface/transformers による DistilBert の実装のドキュメンテーションは 公式ドキュメンテーション を参照のこと.

今回提供する Q-A ボットの Docker のソースコードは https://github.com/andatoshiki/toshiki-notebookblob/main/handson/qa-bot/docker/Dockerfile にある.

アプリケーションの説明

このハンズオンで作成するアプリケーションの概要を figure_title に示す.

アプリケーションのアーキテクチャ

簡単にまとめると,以下のような設計である.

  • クライアントは,質問を AWS 上のアプリケーションに送信する.

  • 質問のタスクは ECS によって処理される.

  • ECS は, Docker Hub から,イメージをダウンロードする.

  • 次に,ECS はクラスター内に新たな Fargate インスタンスを立ち上げ,ダウンロードされた Docker イメージをこの新規インスタンスに配置する.

    • このとき,一つの質問に対し一つの Fargate インスタンスを立ち上げることで,複数の質問を並列的に処理できるようにする.
  • ジョブが実行される.

  • ジョブの実行結果 (質問への回答) は, データベース (DynamoDB) に書き込まれる.

  • 最後に,クライアントは DynamoDB から質問への回答を読み取る.

それでは,プログラムのソースコードを見てみよう (handson/qa-bot/app.py).

sh
class EcsClusterQaBot(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        # dynamoDB table to store questions and answers
        table = dynamodb.Table(
            self, "EcsClusterQaBot-Table",
            partition_key=dynamodb.Attribute(
                name="item_id", type=dynamodb.AttributeType.STRING
            ),
            billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        #
        vpc = ec2.Vpc(
            self, "EcsClusterQaBot-Vpc",
            max_azs=1,
        )

        #
        cluster = ecs.Cluster(
            self, "EcsClusterQaBot-Cluster",
            vpc=vpc,
        )

        #
        taskdef = ecs.FargateTaskDefinition(
            self, "EcsClusterQaBot-TaskDef",
            cpu=1024, # 1 CPU
            memory_limit_mib=4096, # 4GB RAM
        )

        # grant permissions
        table.grant_read_write_data(taskdef.task_role)
        taskdef.add_to_task_role_policy(
            iam.PolicyStatement(
                effect=iam.Effect.ALLOW,
                resources=["*"],
                actions=["ssm:GetParameter"]
            )
        )

        #
        container = taskdef.add_container(
            "EcsClusterQaBot-Container",
            image=ecs.ContainerImage.from_registry(
                "tomomano/qabot:latest"
            ),
        )
class EcsClusterQaBot(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        # dynamoDB table to store questions and answers
        table = dynamodb.Table(
            self, "EcsClusterQaBot-Table",
            partition_key=dynamodb.Attribute(
                name="item_id", type=dynamodb.AttributeType.STRING
            ),
            billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        #
        vpc = ec2.Vpc(
            self, "EcsClusterQaBot-Vpc",
            max_azs=1,
        )

        #
        cluster = ecs.Cluster(
            self, "EcsClusterQaBot-Cluster",
            vpc=vpc,
        )

        #
        taskdef = ecs.FargateTaskDefinition(
            self, "EcsClusterQaBot-TaskDef",
            cpu=1024, # 1 CPU
            memory_limit_mib=4096, # 4GB RAM
        )

        # grant permissions
        table.grant_read_write_data(taskdef.task_role)
        taskdef.add_to_task_role_policy(
            iam.PolicyStatement(
                effect=iam.Effect.ALLOW,
                resources=["*"],
                actions=["ssm:GetParameter"]
            )
        )

        #
        container = taskdef.add_container(
            "EcsClusterQaBot-Container",
            image=ecs.ContainerImage.from_registry(
                "tomomano/qabot:latest"
            ),
        )
  • ここでは,回答の結果を書き込むためのデータベースを用意している. DynamoDB については,サーバーレスアーキテクチャの章で扱うので,今は気にしなくてよい.

  • ここでは,ハンズオン #1, #2 で行ったのと同様に, VPC を定義している.

  • ここで, ECS のクラスター (cluster) を定義している. クラスターとは,仮想サーバーのプールのことであり,クラスターの中に複数の仮想インスタンスを配置する.

  • ここで,実行するタスクを定義している (task definition).

  • ここで, タスクの実行で使用する Docker イメージを定義している.

ECS と Fargate

ECS と Fargate の部分について,コードをくわしく見てみよう.

sh
cluster = ecs.Cluster(
    self, "EcsClusterQaBot-Cluster",
    vpc=vpc,
)

taskdef = ecs.FargateTaskDefinition(
    self, "EcsClusterQaBot-TaskDef",
    cpu=1024, # 1 CPU
    memory_limit_mib=4096, # 4GB RAM
)

container = taskdef.add_container(
    "EcsClusterQaBot-Container",
    image=ecs.ContainerImage.from_registry(
        "tomomano/qabot:latest"
    ),
)
cluster = ecs.Cluster(
    self, "EcsClusterQaBot-Cluster",
    vpc=vpc,
)

taskdef = ecs.FargateTaskDefinition(
    self, "EcsClusterQaBot-TaskDef",
    cpu=1024, # 1 CPU
    memory_limit_mib=4096, # 4GB RAM
)

container = taskdef.add_container(
    "EcsClusterQaBot-Container",
    image=ecs.ContainerImage.from_registry(
        "tomomano/qabot:latest"
    ),
)

cluster = の箇所で,空の ECS クラスターを定義している.

次に, taskdef=ecs.FargateTaskDefinition の箇所で, Fargate インスタンスを使ったタスクを定義しており,とくにここでは 1 CPU, 4GB RAM というマシンスペックを指定している. また,このようにして定義されたタスクは,デフォルトで 1 タスクにつき 1 インスタンスが使用される.

最後に, container = の箇所で,タスクの実行で使用する Docker image を定義している. ここでは, Docker Hub に置いてある image をダウンロードしてくるよう指定している.

このようにわずか数行のコードであるが,これだけで前述したような,タスクのスケジューリングなどが自動で実行される.

このコードで cpu=1024 と指定されているのに注目してほしい. これは CPU ユニットと呼ばれる数で, 以下の換算表に従って仮想 CPU (virtual CPU; vCPU) が割り当てられる. 1024 が 1 CPU に相当する. 0.25 や 0.5 vCPU などの数字は,それぞれ実効的に 1/4, 1/2 の CPU 時間が割り当てられることを意味する. また, CPU ユニットによって使用できるメモリー量も変わってくる. たとえば, 1024 CPU ユニットを選択した場合は, 2 から 8 GB の範囲でのみメモリー量を指定することができる. 最新の情報は 公式ドキュメンテーション "Amazon ECS on AWS Fargate" を参照のこと.

CPU ユニットと 指定可能なメモリー量の換算表

CPU ユニット

メモリーの値

256 (.25 vCPU)

0.5 GB, 1 GB, 2 GB

512 (.5 vCPU)

1 GB, 2 GB, 3 GB, 4 GB

1024 (1 vCPU)

2 GB, 3 GB, 4 GB, 5 GB, 6 GB, 7 GB, 8 GB

2048 (2 vCPU)

Between 4 GB and 16 GB in 1-GB increments

4096 (4 vCPU)

Between 8 GB and 30 GB in 1-GB increments

スタックのデプロイ

スタックの中身が理解できたところで,早速スタックをデプロイしてみよう.

デプロイの手順は,これまでのハンズオンとほとんど共通である. SSH によるログインの必要がないので,むしろ単純なくらいである. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). それぞれの意味を忘れてしまった場合は,ハンズオン 1, 2 に戻って復習していただきたい. シークレットキーの設定も忘れずに (AWS CLI のインストール).

sh
# プロジェクトのディレクトリに移動
$ cd handson/qa-bot

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd handson/qa-bot

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイのコマンドが無事に実行されれば, figure_title のような出力が得られるはずである.

CDKデプロイ実行後の出力

AWS コンソールにログインして,デプロイされたスタックの中身を確認してみよう. コンソールから,ECS のページに行くと figure_title のような画面が表示されるはずである. EcsClusterQaBot-XXXX という名前ついたクラスターを見つけよう.

Cluster というのが,先ほど説明したとおり,複数の仮想インスタンスを束ねる一つの単位である. figure_title で, FARGATE という文字の下に 0 Running tasks, 0 Pending tasks と表示されていることを確認しよう. この時点では一つもタスクが走っていないので,数字はすべて 0 になっている.

ECS コンソール画面

続いて,この画面の左のメニューバーから Task Definitions という項目を見つけ,クリックしよう. 移動した先のページで EcsClusterQaBotEcsClusterQaBotTaskDefXXXX という項目が見つかるので,開く. 開いた先のページをスクロールすると figure_title に示したような情報が見つかるだろう. 使用する CPU ・メモリーの量や, Docker container の実行に関する設定などが,この Task Definition の画面から確認することができる.

Task definition の確認

タスクの実行

それでは,質問をデプロイしたクラウドに提出してみよう.

ECS にタスクを投入するのはやや複雑なので,タスクの投入を簡単にするプログラム (run_task.py) を用意した (handson/qa-bot/run_task.py).

次のようなコマンドで,ECS クラスターに新しい質問を投入することができる.

sh
$ python run_task.py ask "A giant peach was flowing in the river. She picked it up and brought it home. Later, a healthy baby was born from the peach. She named the baby Momotaro." "What is the name of the baby?"
$ python run_task.py ask "A giant peach was flowing in the river. She picked it up and brought it home. Later, a healthy baby was born from the peach. She named the baby Momotaro." "What is the name of the baby?"

run_task.py を実行するには, コマンドラインで AWS の認証情報が設定されていることが前提である.

"ask" の引数に続き,文脈 (context) と質問 (question) を引数として渡している.

このコマンドを実行すると, "Waiting for the task to finish…" と出力が表示され,回答を得るまでしばらく待たされる. この間, AWS では ECS がタスクを受理し,新しい Fargate のインスタンスを起動し, Docker イメージをそのインスタンスに配置する,という一連の処理がなされている. AWS コンソールから,この一連の様子をモニタリングしてみよう.

先ほどの ECS コンソール画面にもどり,クラスターの名前をクリックすることで,クラスターの詳細画面を開く. 次に, "Tasks" という名前のタブがあるので,それを開く (figure_title). すると,実行中のタスクの一覧が表示されるだろう.

ECS のタスクの実行状況をモニタリング

figure_title で見て取れるように, "Last status = Pending" となっていることから,この時点では,タスクを実行する準備をしている段階である,ということがわかる. Fargate のインスタンスを起動し, Docker image を配置するまでおよそ 1-2 分の時間がかかる.

しばらく待つうちに, Status が "RUNNING" に遷移し,計算が始まる. 計算が終わると, Status は "STOPPED" に遷移し, ECS によって Fargate インスタンスは自動的にシャットダウンされる.

figure_title の画面から, "Task" の列にあるタスク ID クリックすることで,タスクの詳細画面を開いてみよう (figure_title). "Last status", "Platform version" など,タスクの情報が表示されている. また, "Logs" のタブを開くことで,コンテナの吐き出した実行ログを閲覧することができる.

質問タスクの実行結果

さて, run_task.py を実行したコマンドラインに戻ってきてみると, figure_title のような出力が得られているはずである. "Momotaro" という正しい回答が返ってきている!

質問タスクの実行結果

タスクの同時実行

さて,先ほどはたった一つの質問を投入したわけだが,今回設計したアプリケーションは, ECS と Fargate を使うことで同時にたくさんの質問を処理することができる. 実際に,たくさんの質問を一度に投入してみよう. run_task.pyask_many というオプションを付けることで,複数の質問を一度に送信できる. 質問の内容は handson/qa-bot/problems.json に定義されている.

次のようなコマンドを実行しよう.

sh
$ python run_task.py ask_many
$ python run_task.py ask_many

このコマンドを実行した後で,先ほどの ECS コンソールに行き,タスクの一覧を見てみよう (figure_title). 複数の Fargate インスタンスが起動され,タスクが並列に実行されているのがわかる.

複数の質問タスクを同時に投入する

すべてのタスクのステータスが "STOPPED" になったことを確認した上で,質問への回答を取得しよう. それには,次のコマンドを実行する.

sh
$ python run_task.py list_answers
$ python run_task.py list_answers

結果として, figure_title のような出力が得られるだろう. 複雑な文章問題に対し,高い正答率で回答できていることがわかるだろう.

 の実行結果

おめでとう! ここまでついてこれた読者はとても初歩的ながらも,深層学習による言語モデルを使って自動で質問への回答を生成するシステムを創り上げることができた! それも,数百の質問にも同時に対応できるような,とても高いスケーラビリティーをもったシステムである! 今回は GUI (Graphical User Interface) を用意することはしなかったが,このシステムに簡単な GUI を追加すればなかなか立派なウェブサービスとして運用できるだろう.

run_task.py で質問を投入し続けると,回答を記録しているデータベースにどんどんエントリーが溜まっていく. これらのエントリーをすべて消去するには,次のコマンドを使う.

sh
$ python run_task.py clear
$ python run_task.py clear

スタックの削除

これにて,今回のハンズオンは終了である. 最後にスタックを削除しよう.

スタックを削除するには,前回までと同様に, AWS コンソールにログインし CloudFormation の画面から DELETE ボタンをクリックするか,コマンドラインからコマンドを実行する. コマンドラインから行う場合は,次のコマンドを使用する.

sh
$ cdk destroy
$ cdk destroy

Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する

ハンズオン第三回では, ECS と Fargate を使って自動質問回答システムを構築した. シンプルながらも,複数の質問が送られた場合には並列にジョブが実行され,ユーザーに答えが返されるシステムを作ることができた. ここでは,すでに学習済みの言語モデルを用いてアプリケーションを構築した. しかし,一般的に言って,機械学習のワークフローでは自分で作ったモデルを訓練することが最初のステップにあるはずである. そこで,ハンズオン第四回では,クラウドを用いて機械学習の訓練を並列化・高速化することを考える.

本ハンズオンでは深層学習におけるハイパーパラメータ最適化を取り上げる. ハイパーパラメータとは,勾配降下法によって最適化されるニューラルネットのパラメータの外にあるパラメータのことであり,具体的にはモデルの層の幅・深さなどネットワークのアーキテクチャに関わるもの,学習率やモメンタムなどパラメータの更新則に関わるものなどが含まる. 深層学習においてハイパーパラメータの調整はとても重要なタスクである. しかしながら,ハイパーパラメータを調整するには,少しずつ条件を変えながら何度もニューラルネットを学習させる必要があり,多くの計算時間がかかる. 研究・開発においては,スループットよくたくさんのモデルの可能性を探索することが生産性を決める重要なファクターであり,ハイパーパラメータ探索を高速に解くという問題は極めて関心が高い. 本ハンズオンでは,クラウドの強力な計算リソースを利用して並列的にニューラルネットの訓練を実行することで,この問題を解く方法を学んでいこう.

Auto scaling groups (ASG)

ハンズオンに入っていく前に, Auto scaling groups (ASG) とよばれる EC2 の概念を知っておく必要がある.

ECS の概要を示した figure_title を振り返って見てほしい. 前章 (Hands-on #3: AWS で自動質問回答ボットを走らせる) でも説明したが, ECS のクラスターで計算を担う実体としては EC2 と Fargate を指定することができる. Fargate については前章で記述した. Fargate を用いると,自在にスケールする計算環境をとても簡単な設定で構築することができた. しかし, GPU を利用することができないなど,いくつかの制約があった. EC2 を使用した計算環境を指定することで,プログラミングの複雑度は増すが, GPU やその他のより高度かつ複雑な設定を伴ったクラスターを構築することができる.

EC2 クラスターには ASG と呼ばれるサービスが配置される. ASG は複数の EC2 インスタンスをロジカルな単位でグループ化することでクラスターを構成する. ASG はクラスター内に新しいインスタンスを起動する,あるいは不要になったインスタンスを停止するなどのスケーリングを担う. ASG で重要な概念として, desired capacity, minimum capacity, maximum capacity というパラメータがある. minimum capacity, maximum capacity は,それぞれクラスター内に配置できるインスタンスの数の最小値・最大値を指定するパラメータである. 前者は,クラスターに負荷がかかっていない場合でもアイドリング状態にあるインスタンスを維持することで,急に負荷が増大した時などのバッファーとして作用することができる. 後者は,負荷が急に増えたときに,過剰な数のインスタンスが起動する事態を防ぎ,経済的なコストの上限を定める役割を果たす.

desired capacity が,その時々でシステムが要求するインスタンスの数を指定する. desired capacity は,例えば 24 時間のリズムに合わせてインスタンスの数を増減させる (昼は多く夜は少なくなど) などの決まったスケジュールに基づいた設定を適用することができる. あるいはクラスター全体にかかっている負荷に応じて, desired capacity を動的に制御することも可能である. どのような基準でクラスターのスケーリングを行うかを定めるルールのことを,スケーリングポリシーとよぶ. たとえば,クラスター全体の稼働率 (負荷) を常に 80% に維持する,などのスケーリングポリシーが想定できる. この場合,クラスター全体の負荷が 80%を下回ったときにはクラスターからインスタンスが削除され,80%を超える (あるいは超えると予測される) 場合はインスタンスを追加する,という操作が ASG によって自動的に行われる.

上記のようなパラメータを検討し,ユーザーは ASG を作成する. ASG を作成したのち, ECS との連携をプログラムしてあげることで, ECS を介して ASG による EC2 クラスターにタスクを投入することが可能になる.

AWS Batch

AWS Batch のアイコン

先に説明したように, ECS と ASG を組み合わせることで,所望の計算クラスターを構築することが可能である. しかしながら, ECS と ASG にはかなり込み入った設定が必要であり,初心者にとっても経験者にとってもなかなか面倒なプログラミングが要求される. そこで, ECS と ASG によるクラスターの設計を自動化してくれるサービスが提供されている. それが AWS Batch である.

AWS Batch はその名のとおりバッチ (Batch) 化されたジョブ (入力データだけが異なる独立した演算が繰り返し実行されること) を想定している. 多くの科学計算や機械学習がバッチ計算に当てはまる. たとえば,初期値のパラメータを変えて複数のシミュレーションを走らせる,といったケースだ. AWS Batch を用いることの利点は,クラスターのスケーリングやジョブの割り振りはすべて自動で実行され, ユーザーはクラウドの舞台裏の詳細を気にすることなく,大量のジョブを投入できるシステムが手に入る点である. が,知識として背後では ECS/ASG/EC2 の三つ巴が協調して動作しているという点は知っておいてほしい.

AWS Batch では,ジョブの投入・管理をスムーズに行うため,次のような概念が定義されている (figure_title). まず, ジョブ (Job) というのが,AWS Batch によって実行される一つの計算の単位である. Job definitions とはジョブの内容を定義するものであり,これには実行されるべき Docker のイメージのアドレスや,割り当てる CPU・RAM の容量,環境変数などの設定が含まれる. Job definition に基づいて個々のジョブが実行される. ジョブが実行されると,ジョブは Job queues に入る. Job queues とは,実行待ち状態にあるジョブの列のことであり,時間的に最も先頭に投入されたジョブが最初に実行される. また,複数の queue を配置し, queue ごとに priority (優先度) を設定することが可能であり, priority の高い queue に溜まったジョブが優先的に実行される (筆者はこれをディズニーランドの"ファストパス"を連想して捉えている). Compute environment とは,先述したクラスターとほぼ同義の概念であり,計算が実行される場所 (EC2 や Fargate からなるクラスター) を指す. Compute environment には,使用する EC2 のインスタンスタイプや同時に起動するインスタンス数の上限などの簡易なスケーリングポリシーが指定されている. Job queues は Compute environment の空き状況を監視しており, それに応じてジョブを Compute environment に投下する.

以上が AWS Batch を使用するうえで理解しておかなければならない概念であるが,くどくど言葉で説明してもなかなかピンとこないだろう. ここからは,実際に自分で手を動かしながら学んでいこう.

AWS Batch の主要な概念

EC2 or Fargate?

ECS でクラスターを構成する際,計算を実行する場として EC2 と Fargate の二つの選択肢があることを説明した. それぞれ長所と短所を抱えているのだが,どのような場合にどちらを使うべきだろうか? それを検討するため,まずは table_title を見てみよう. これは EC2 と Fargate の特徴をまとめたものである. 説明の都合上,大幅な粗視化が行われている点は留意していただきたい.

EC2 vs Fargate
EC2Fargate

Compute capacity

Medium to large

Small to medium

GPU

Yes

No

Launch speed

Slow

Fast

Task placement flexibility

Low

High

Programming complexity

High

Low

これまでに見てきたように, EC2 は最大の CPU 数・メモリーサイズが大きかったり, GPU を利用できたりするなど,単一のインスタンスでの計算能力は高い. 対して, Fargate は単一インスタンスの最大 CPU 数は 4 コアが上限である. その一方で,インスタンスの起動に要する時間は Fargate のほうが圧倒的に早く,より俊敏にクラスターのスケーリングを行うことができる. また,タスクをクラスターに投入する際のフレキシビリティも Fargate のほうが高い. フレキシビリティというのは,例えば一つのインスタンスで 2 つ以上のコンテナを走らせる,などの状況である. 単位 CPU あたりで処理されるタスクの数を最大化する際には,このような設計がしばしば採用される. プログラミングの複雑さという観点からは, Fargate のほうが一般的にシンプルな実装になる.

このように, EC2 と Fargate は互いに相補的な特性を有しており,アプリケーションによって最適な計算環境は検討される必要がある. また,EC2 と Fargate を両方用いたハイブリッドクラスターというのも定義可能であり,そのような選択肢もしばしば用いられる.

準備

ハンズオンのソースコードは GitHub の handson/aws-batch にある.

本ハンズオンの実行には,第一回ハンズオンで説明した準備 (準備) が整っていることを前提とする. また, Docker が自身のローカルマシンにインストール済みであることも必要である.

このハンズオンは, g4dn.xlarge タイプの EC2 インスタンスを使うので,アメリカ東部 (us-east-1) リージョンでは 0.526 $/hour のコストが発生する. 東京 (ap-northeast-1) を選択した場合は 0.71 $/hour のコストが発生する.

準備 でも注意したが,このハンズオンを始める前に G タイプインスタンスの起動上限を AWS コンソールの EC2 管理画面から確認しよう. もし上限が 0 になっていた場合は,上限緩和の申請を行う必要がある. アプリケーションの説明 にも関連した情報を記載しているので,併せて参照されたい.

MNIST 手書き文字認識 (再訪)

今回のハンズオンでは,機械学習のハイパーパラメータ調整を取り上げると冒頭で述べた. その最もシンプルな例題として, 実践ディープラーニング! MNIST 手書き数字認識タスク で扱った MNIST 手書き文字認識の問題を再度取り上げよう. 実践ディープラーニング! MNIST 手書き数字認識タスク では,適当にチョイスしたハイパーパラメータを用いてモデルの訓練を行った. ここで使用したプログラムのハイパーパラメータとしては,確率的勾配降下法 (SGD) における学習率やモメンタムが含まれる. コードでいうと,次の行が該当する.

python
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)

ここで使用された 学習率 (lr=0.01) やモメンタム (momentum=0.5) は恣意的に選択された値であり,これがベストな数値であるのかはわからない. たまたまこのチョイスが最適であるかもしれないし,もっと高い精度を出すハイパーパラメータの組が存在するかもしれない. この問題に答えるため,ハイパーパラメータサーチを行おう. 今回は,最もシンプルなアプローチとして,グリッドサーチによるハイパーパラメータサーチを行おう.

機械学習のハイパーパラメータの最適化には大きく3つのアプローチが挙げられる. グリッドサーチ,ランダムサーチ,そしてベイズ最適化による方法である.

グリッドサーチとは,ハイパーパラメータの組をある範囲の中で可能な組み合わせをすべて計算し,最適なパラメータの組を見出す方法である. 最もシンプルかつ確実な方法であるが,すべての組み合わせの可能性を愚直に計算するので計算コストが大きい.

ランダムサーチ法とは,ハイパーパラメータの組をある範囲の中でランダムに抽出し,大量に試行されたランダムな組の中から最適なパラメータの組を見出す方法である. すべての可能性を網羅的に探索できるわけではないが,調整すべきパラメータの数が多数ある場合に,グリッドサーチよりも効率的に広い探索空間をカバーすることができる.

ベイズ最適化を用いた方法では,過去の探索結果から次にどの組み合わせを探索すべきかという指標を計算し,次に探索するパラメータを決定する. これにより,理論的にはグリッドサーチやランダムサーチ法よりも少ない試行回数で最適なパラメータにたどり着くことができる.

並列化の観点でいうと,グリッドサーチとランダムサーチは各ハイパーパラメータの組の計算は独立に実行することができるため並列化が容易である. このように独立したジョブとして分割・並列化可能な問題を Embarrassingly parallel な問題とよぶ (直訳すると"恥ずかしいほど並列化可能な問題",ということになる). Embarrassingly parallel な問題はクラウドの強力な計算リソースを用いることで,非常なシンプルな実装で解くことができる. この章ではこのようなタイプの並列計算を取り上げる.

一方,ベイズ最適化による方法は,過去の結果をもとに次の探索が決定されるので,並列化はそれほど単純ではない. 最近では optuna などのハイパーパラメータ探索のためのライブラリが発達しており,ベイズ最適化の数理的な処理を自動で実行してくれるので便利である. これらのライブラリを使うと,もし一台のコンピュータ (ノード) の中に複数の GPU が存在する場合は,並列に計算を実行することができる. しかしながら,一台のノードにとどまらず,複数のノードをまたいだ並列化は,高度なプログラミングテクニックが必要とされるだけでなく,ノード間の接続様式などクラウドのアーキテクチャにも深く依存するものである. 本書ではここまで高度なクラウドの使用方法には立ち入らない.

まずは,本ハンズオンで使用する Docker イメージをローカルで実行してみよう.

Docker イメージのソースコードは handson/aws-batch/docker にある. 基本的に 実践ディープラーニング! MNIST 手書き数字認識タスク のハンズオンを元にし,本ハンズオン専用の軽微な変更が施してある. 興味のある読者はソースコードも含めて読んでいただきたい.

練習として,この Docker イメージを手元でビルドするところからはじめてみよう. Dockerfile が保存されているディレクトリに移動し, mymnist という名前 (Tag) をつけてビルドを実行する.

sh
$ cd handson/aws-batch/docker
$ docker build -t mymnist .
$ cd handson/aws-batch/docker
$ docker build -t mymnist .

docker build でエラーが出たときは次の可能性を疑ってほしい. ビルドの中で, MNIST の画像データセットを http://yann.lecun.com/exdb/mnist/ からダウンロードするのだが,ダウンロード先のサーバーがしばしばダウンしている. 世界中の機械学習ユーザーがアクセスするので,これはしばしば発生するようである. サーバーがダウンしているとビルドも失敗してしまう. エラーメッセージにそれらしい文言が含まれていたら,この可能性を疑おう.

手元でビルドするかわりに, Docker Hub から pull することも可能である. その場合は次のコマンドを実行する.

sh
$ docker pull tomomano/mymnist:latest
$ docker pull tomomano/mymnist:latest

イメージの準備ができたら,次のコマンドでコンテナを起動し, MNIST の学習を実行する..

sh
$ docker run mymnist --lr 0.1 --momentum 0.5 --epochs 10
$ docker run mymnist --lr 0.1 --momentum 0.5 --epochs 10

このコマンドを実行すると,指定したハイパーパラメータ (--lr で与えられる学習率と --momentum で与えられるモメンタム) を使ってニューラルネットの最適化が始まる. 学習を行う最大のエポック数は --epochs パラメータで指定する. Hands-on #2: AWS でディープラーニングを実践 のハンズオンで見たような, Loss の低下がコマンドライン上に出力されるだろう (figure_title).

Docker を実行した際の出力

上に示したコマンドを使うと,計算は CPU を使って実行される. もし,ローカルの計算機に GPU が備わっており, nvidia-docker の設定が済んでいるならば, 次のコマンドにより GPU を使って計算を実行できる.

sh
$ docker run --gpus all mymnist --lr 0.1 --momentum 0.5 --epochs 10
$ docker run --gpus all mymnist --lr 0.1 --momentum 0.5 --epochs 10

このコマンドでは,--gpus all というパラメータが加わった.

CPU/GPU どちらで実行した場合でも,エポックを重ねるにつれて訓練データ (Train データ) の Loss は単調に減少していくのが見て取れるだろう. 一方,検証データ (Validation データ) の Loss および Accuracy は,ある程度まで減少した後,それ以上性能が向上しないことに気がつくだろう. これを実際にプロットしてみると figure_title のようになるはずである.

(左) Train/Validation データそれぞれの Loss のエポックごとの変化. (右) Validation データの Accuracy のエポックごとの変化

これはオーバーフィッティングとよばれる現象で,ニューラルネットが訓練データに過度に最適化され,訓練データの外のデータに対しての精度 (汎化性能) が向上していないことを示している. このような場合の対処法として, Early stopping とよばれるテクニックが知られている. Early stopping とは,検証データの Loss を追跡し,それが減少から増加に転じるエポックで学習をうち止め,そのエポックでのウェイトパラメータを採用する,というものである. 本ハンズオンでも, Early stopping によって訓練の終了を判断し,モデルの性能評価を行っていく.

MNIST 手書き文字データセットでは,訓練データとして 60,000 枚,テストデータとして 10,000 枚の画像が与えられている. 本ハンズオンで使用するコードでは,訓練データのうち 80% の 48,000 枚を訓練データとして使用し,残り 20% の 12,000 枚を検証データとして用いている. 詳しくはソースコードを参照のこと.

アプリケーションの説明

このハンズオンで作成するアプリケーションの概要を figure_title に示す.

アプリケーションのアーキテクチャ

簡単にまとめると,次のような設計である.

  • クライアントは,あるハイパーパラメータの組を指定して Batch にジョブを提出する

  • Batch はジョブを受け取ると, EC2 からなるクラスターで計算を実行する

  • クラスター内では g4dn.xlarge インスタンスが起動する

  • Docker イメージは, AWS 内に用意された ECR (Elastic Container Registry) から取得される

  • 複数のジョブが投下された場合は,その数だけのインスタンスが起動し並列に実行される

  • 各ジョブによる計算の結果は S3 に保存される

  • 最後にクライアントは S3 から結果をダウンロードし,最適なハイパーパラメータの組を決定する

それでは,プログラムのソースコードを見てみよう (handson/aws-batch/app.py).

python
class SimpleBatch(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        bucket = s3.Bucket(
            self, "bucket",
            removal_policy=core.RemovalPolicy.DESTROY,
            auto_delete_objects=True,
        )

        vpc = ec2.Vpc(
            self, "vpc",
            # other parameters...
        )

        #
        managed_env = batch.ComputeEnvironment(
            self, "managed-env",
            compute_resources=batch.ComputeResources(
                vpc=vpc,
                allocation_strategy=batch.AllocationStrategy.BEST_FIT,
                desiredv_cpus=0,
                maxv_cpus=64,
                minv_cpus=0,
                instance_types=[
                    ec2.InstanceType("g4dn.xlarge")
                ],
            ),
            managed=True,
            compute_environment_name=self.stack_name + "compute-env"
        )

        #
        job_queue = batch.JobQueue(
            self, "job-queue",
            compute_environments=[
                batch.JobQueueComputeEnvironment(
                    compute_environment=managed_env,
                    order=100
                )
            ],
            job_queue_name=self.stack_name + "job-queue"
        )

        #
        job_role = iam.Role(
            self, "job-role",
            assumed_by=iam.CompositePrincipal(
                iam.ServicePrincipal("ecs-tasks.amazonaws.com")
            )
        )
        # allow read and write access to S3 bucket
        bucket.grant_read_write(job_role)

        #
        repo = ecr.Repository(
            self, "repository",
            removal_policy=core.RemovalPolicy.DESTROY,
        )

        #
        job_def = batch.JobDefinition(
            self, "job-definition",
            container=batch.JobDefinitionContainer(
                image=ecs.ContainerImage.from_ecr_repository(repo),
                command=["python3", "main.py"],
                vcpus=4,
                gpu_count=1,
                memory_limit_mib=12000,
                job_role=job_role,
                environment={
                    "BUCKET_NAME": bucket.bucket_name
                }
            ),
            job_definition_name=self.stack_name + "job-definition",
            timeout=core.Duration.hours(2),
        )
class SimpleBatch(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        bucket = s3.Bucket(
            self, "bucket",
            removal_policy=core.RemovalPolicy.DESTROY,
            auto_delete_objects=True,
        )

        vpc = ec2.Vpc(
            self, "vpc",
            # other parameters...
        )

        #
        managed_env = batch.ComputeEnvironment(
            self, "managed-env",
            compute_resources=batch.ComputeResources(
                vpc=vpc,
                allocation_strategy=batch.AllocationStrategy.BEST_FIT,
                desiredv_cpus=0,
                maxv_cpus=64,
                minv_cpus=0,
                instance_types=[
                    ec2.InstanceType("g4dn.xlarge")
                ],
            ),
            managed=True,
            compute_environment_name=self.stack_name + "compute-env"
        )

        #
        job_queue = batch.JobQueue(
            self, "job-queue",
            compute_environments=[
                batch.JobQueueComputeEnvironment(
                    compute_environment=managed_env,
                    order=100
                )
            ],
            job_queue_name=self.stack_name + "job-queue"
        )

        #
        job_role = iam.Role(
            self, "job-role",
            assumed_by=iam.CompositePrincipal(
                iam.ServicePrincipal("ecs-tasks.amazonaws.com")
            )
        )
        # allow read and write access to S3 bucket
        bucket.grant_read_write(job_role)

        #
        repo = ecr.Repository(
            self, "repository",
            removal_policy=core.RemovalPolicy.DESTROY,
        )

        #
        job_def = batch.JobDefinition(
            self, "job-definition",
            container=batch.JobDefinitionContainer(
                image=ecs.ContainerImage.from_ecr_repository(repo),
                command=["python3", "main.py"],
                vcpus=4,
                gpu_count=1,
                memory_limit_mib=12000,
                job_role=job_role,
                environment={
                    "BUCKET_NAME": bucket.bucket_name
                }
            ),
            job_definition_name=self.stack_name + "job-definition",
            timeout=core.Duration.hours(2),
        )
  • で,計算結果を保存するための S3 バケットを用意している

  • で, Compute environment を定義している. ここでは g4dn.xlarge のインスタンスタイプを使用するとし,最大の vCPU 使用数は 64 と指定している. また,最小の vCPU は 0 である. 今回は,負荷がかかっていないときにアイドリング状態にあるインスタンスを用意する利点は全くないので,ここは 0 にするのが望ましい.

  • で, <2> で作成した Compute environment と紐付いた Job queue を定義している.

  • で,ジョブが計算結果を S3 に書き込むことができるよう, IAM ロールを定義している. (IAM とはリソースがもつ権限を管理する仕組みである.詳しくは AWS における権限の管理 (IAM) を参照)

  • では, Docker image を配置するための ECR を定義している.

  • で Job definition を作成している. ここでは,4 vCPU, 12000 MB (=12GB) の RAM を使用するように指定している. また,今後必要となる環境変数 (BUCKET_NAME) を設定している. さらに, <4> で作った IAM を付与している.

g4dn.xlarge は 1 台あたり 4 vCPU が割り当てられている. このプログラムでは Compute environment の maximum vCPUs を 64 と指定しているので,最大で 16 台のインスタンスが同時に起動することになる. ここで maxium vCPUs を 64 に限定しているのは,なんらかのミスで意図せぬジョブを大量にクラスターに投入してしまった事態で,高額の AWS 利用料金が発生するのを防ぐためである. もし,自分のアプリケーションで必要と判断したならば自己責任において 64 よりも大きな数を設定して構わない.

ここで注意が一点ある. AWS では各アカウントごとに EC2 で起動できるインスタンスの上限が設定されている. この上限は AWS コンソールにログインし, EC2 コンソールの左側メニューバーの Limits をクリックすることで確認できる (figure_title). g4dn.xlarge (EC2 の区分でいうと G ファミリーに属する) の制限を確認するには, Running On-Demand All G instances という名前の項目を見る. ここにある数字が, AWS によって課されたアカウントの上限であり,この上限を超えたインスタンスを起動することはできない. もし,自分の用途に対して上限が低すぎる場合は,上限の緩和申請を行うことができる. 詳しくは 公式ドキュメンテーション "Amazon EC2 service quotas" を参照のこと.

EC2コンソールから各種の上限を確認する

スタックのデプロイ

スタックの中身が理解できたところで,早速スタックをデプロイしてみよう.

デプロイの手順は,これまでのハンズオンとほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). シークレットキーの設定も忘れずに (AWS CLI のインストール).

sh
# プロジェクトのディレクトリに移動
$ cd handson/aws-batch

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd handson/aws-batch

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイのコマンドが無事に実行されたことが確認できたら,AWS コンソールにログインして,デプロイされたスタックを確認してみよう. コンソールの検索バーで batch と入力し, AWS Batch の管理画面を開く (figure_title).

AWS Batch のコンソール画面 (ダッシュボード)

まず目を向けてほしいのが,画面の一番下にある Compute environment overview の中の SimpleBatchcompute-env という名前の項目だ. Compute environment とは,先ほど述べたとおり,計算が実行される環境 (クラスターと読み替えてもよい) である. プログラムで指定したとおり, g4dn.xlarge が実際に使用されるインスタンスタイプとして表示されている. また, Minimum vCPUs が 0,Maximum vCPUs が 64 と設定されていることも見て取れる. 加えて,この時点では一つもジョブが走っていないので, Desired vCPUs は 0 になっている. より詳細な Compute environment の情報を閲覧したい場合は,名前をクリックすることで詳細画面が開く.

次に,Job queue overview にある SimpleBatch-queue という項目に注目してほしい. ここでは実行待ちのジョブ・実行中のジョブ・実行が完了したジョブを一覧で確認することができる. PENDING, RUNNING, SUCCEEDED, FAILED などのカラムがあることが確認できる.ジョブが進行するにつれて,ジョブの状態がこのカラムにしたがって遷移していく. 後でジョブを実際にサブミットしたときに戻ってこよう.

最後に,今回作成した Job definition を確認しよう. 左側のメニューから Job definitions を選択し,次の画面で SimpleBatchjob-definition という項目を見つけて開く. ここから Job definition の詳細を閲覧することができる (figure_title). 中でも重要な情報としては, vCPUs, Memory, GPU がそれぞれ Docker に割り当てられる vCPU・メモリー・ GPU の量を規定している. また, Image と書いてあるところに,ジョブで使用される Docker イメージが指定されている. ここでは, ECR のレポジトリを参照している. 現時点ではこの ECR は空である. 次のステップとして,この ECR にイメージを配置する作業を行おう.

AWS Batch から Job definition を確認

Docker image を ECR に配置する

さて, Batch がジョブを実行するには,どこか指定された場所から Docker イメージをダウンロード (pull) してくる必要がある. 前回のハンズオン (Hands-on #3: AWS で自動質問回答ボットを走らせる) では,公開設定にしてある Docker Hub からイメージを pull してきた. 今回のハンズオンでは, AWS から提供されているレジストリである ECR (Elastic Container Registry) に image を配置するという設計を採用する. ECR を利用する利点は,自分だけがアクセスすることのできるプライベートなイメージの置き場所を用意できる点である. Batch は ECR からイメージを pull してくることで,タスクを実行する (figure_title).

スタックのソースコードでいうと,次の箇所が ECR を定義している.

python
#
repo = ecr.Repository(
    self, "repository",
    removal_policy=core.RemovalPolicy.DESTROY,
)

job_def = batch.JobDefinition(
    self, "job-definition",
    container=batch.JobDefinitionContainer(
        image=ecs.ContainerImage.from_ecr_repository(repo), #
        ...
    ),
    ...
)
#
repo = ecr.Repository(
    self, "repository",
    removal_policy=core.RemovalPolicy.DESTROY,
)

job_def = batch.JobDefinition(
    self, "job-definition",
    container=batch.JobDefinitionContainer(
        image=ecs.ContainerImage.from_ecr_repository(repo), #
        ...
    ),
    ...
)
  • で,新規の ECR を作成している.

  • で Job definition を定義する中で,イメージを <1> で作った ECR から取得するように指定している. これと同時に, Job definition には ECR へのアクセス権限が IAM を通じて自動的に付与される.

さて,スタックをデプロイした時点では, ECR は空っぽである. ここに自分のアプリケーションで使う Docker イメージを push してあげる必要がある.

そのために,まずは AWS コンソールから ECR の画面を開こう (検索バーに Elastic Container Registry と入力すると出てくる). Private というタブを選択すると, simplebatch-repositoryXXXXXX という名前のレポジトリが見つかるだろう (figure_title).

ECR のコンソール画面

次に,このレポジトリの名前をクリックするとレポジトリの詳細画面に遷移する. そうしたら,画面右上にある View push commands というボタンをクリックする. すると figure_title のようなポップアップ画面が立ち上がる.

ECR への push コマンド

このポップアップ画面で表示されている四つのコマンドを順番に実行していくことで,手元の Docker イメージを ECR に push することができる. push を実行する前に, AWS の認証情報が設定されていることを確認しよう. そのうえで,ハンズオンのソースコードの中にある docker/ という名前のディレクトリに移動する. そうしたら,ポップアップ画面で表示されたコマンドを上から順に実行していく.

ポップアップで表示されるコマンドの 2 つめを見てみると docker build -t XXXXX . となっている. 最後の . が重要で,これは 現在のディレクトリにある Dockerfile を使ってイメージをビルドせよ という意味である. このような理由で, Dockerfile が置いてあるディレクトリに移動する必要がある.

四つ目のコマンドは,数 GB あるイメージを ECR にアップロードするので少し時間がかかるかもしれないが,これが完了するとめでたくイメージが ECR に配置されたことになる. もう一度 ECR のコンソールを見てみると,確かにイメージが配置されていることが確認できる (figure_title). これで,AWS Batch を使ってジョブを実行させるための最後の準備が完了した.

ECR へ image の配置が完了した

単一のジョブを実行する

さて,ここからは実際に AWS Batch にジョブを投入する方法を見ていこう.

ハンズオンのディレクトリの notebook/ というディレクトリの中に, run_single.ipynb というファイルが見つかるはずである (.ipynb は Jupyter notebook のファイル形式). これを Jupyter notebook から開こう.

今回のハンズオンでは, venv による仮想環境の中に Jupyter notebook もインストール済みである. なので,ローカルマシンから以下のコマンドで Jupyter notebook を立ち上げる.

sh
# .env の仮想環境にいることを確認
(.env) $ cd notebook
(.env) $ jupyter notebook
# .env の仮想環境にいることを確認
(.env) $ cd notebook
(.env) $ jupyter notebook

Jupyter notebook が起動したら, run_single.ipynb を開く.

最初の [1], [2], [3] 番のセルは,ジョブをサブミットするための関数 (submit_job()) を定義している.

python
# [1]
import boto3
import argparse

# [2]
# AWS 認証ヘルパー ...省略...

# [3]
def submit_job(lr:float, momentum:float, epochs:int, profile_name="default"):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    client = session.client("batch")

    title = "lr" + str(lr).replace(".", "") + "_m" + str(momentum).replace(".", "")
    resp = client.submit_job(
        jobName=title,
        jobQueue="SimpleBatchjob-queue",
        jobDefinition="SimpleBatchjob-definition",
        containerOverrides={
            "command": ["--lr", str(lr),
                        "--momentum", str(momentum),
                        "--epochs", str(epochs),
                        "--uploadS3", "true"]
        }
    )
    print("Job submitted!")
    print("job name", resp["jobName"], "job ID", resp["jobId"])
# [1]
import boto3
import argparse

# [2]
# AWS 認証ヘルパー ...省略...

# [3]
def submit_job(lr:float, momentum:float, epochs:int, profile_name="default"):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    client = session.client("batch")

    title = "lr" + str(lr).replace(".", "") + "_m" + str(momentum).replace(".", "")
    resp = client.submit_job(
        jobName=title,
        jobQueue="SimpleBatchjob-queue",
        jobDefinition="SimpleBatchjob-definition",
        containerOverrides={
            "command": ["--lr", str(lr),
                        "--momentum", str(momentum),
                        "--epochs", str(epochs),
                        "--uploadS3", "true"]
        }
    )
    print("Job submitted!")
    print("job name", resp["jobName"], "job ID", resp["jobId"])

submit_job() 関数について簡単に説明しよう. MNIST 手書き文字認識 (再訪) で, MNIST の Docker をローカルで実行したとき,次のようなコマンドを使用した.

sh
$ docker run -it mymnist --lr 0.1 --momentum 0.5 --epochs 10
$ docker run -it mymnist --lr 0.1 --momentum 0.5 --epochs 10

ここで, --lr 0.1 --momentum 0.5 --epochs 10 の部分が,コンテナに渡されるコマンドである.

AWS Batch でジョブを実行する際も,ContainerOverridescommand というパラメータを使用することで,コンテナに渡されるコマンドを指定することができる. コードでは以下の部分が該当する.

python
containerOverrides={
    "command": ["--lr", str(lr),
                "--momentum", str(momentum),
                "--epochs", str(epochs),
                "--uploadS3", "true"]
}
containerOverrides={
    "command": ["--lr", str(lr),
                "--momentum", str(momentum),
                "--epochs", str(epochs),
                "--uploadS3", "true"]
}

続いて, [4] 番のセルに移ろう. ここでは,上記の submit_job() 関数を用いて, 学習率 = 0.01, モメンタム=0.1, エポック数=100 を指定したジョブを投入する.

python
# [4]
submit_job(0.01, 0.1, 100)
# [4]
submit_job(0.01, 0.1, 100)

AWS の認証情報は, Jupyter Notebook の内部から再度定義する必要がある. これを手助けするため, Notebook の [2] 番のセル (デフォルトではすべてコメントアウトされている) を用意した. これを使うにはコメントアウトを解除すればよい. このセルを実行すると, AWS の認証情報を入力する対話的なプロンプトが表示される. プロンプトに従って aws secret key などを入力することで, (Jupyter のセッションに固有な) 環境変数に AWS の認証情報が記録される.

もう一つの認証方法として, submit_job() 関数に profile_name というパラメータを用意した. もし ~/.aws/credentials に認証情報が書き込まれているのならば (詳しくは AWS CLI のインストール), profile_name に使用したいプロファイルの名前を渡すだけで, 認証を行うことができる. 慣れている読者は後者のほうが便利であると感じるだろう.

[4] 番のセルを実行したら,ジョブが実際に投入されたかどうかを AWS コンソールから確認してみよう. AWS Batch の管理コンソールを開くと, figure_title のような画面が表示されるだろう.

AWS Batch でジョブが実行されている様子

figure_title で赤で囲った箇所に注目してほしい. 一つのジョブが投入されると,それは SUBMITTED という状態を経て RUNNABLE という状態に遷移する. RUNNABLE とは, ジョブを実行するためのインスタンスが Compute environment に不足しているため,新たなインスタンスが起動されるのを待っている状態に相当する. インスタンスの準備が整うと,ジョブの状態は STARTING を経て RUNNING に至る.

次に,ジョブのステータスが RUNNING のときの Compute environment の Desired vCPU を見てみよう (figure_title で紫で囲った箇所). ここで 4 と表示されているのは, g4dn.xlarge インスタンス一つ分の vCPU の数である. ジョブの投入に応じて,それを実行するのに最低限必要な EC2 インスタンスが起動されたことが確認できる (興味のある人は, EC2 コンソールも同時に覗いてみるとよい).

しばらく経つと,ジョブの状態は RUNNING から SUCCEEDED (あるいは何らかの理由でエラーが発生したときには FAILED) に遷移する. 今回のハンズオンで使っている MNIST の学習はだいたい 10 分くらいで完了するはずである. ジョブの状態が SUCCEEDED になるまで見届けよう.

ジョブが完了すると,学習の結果 (エポックごとの Loss と Accuracy を記録した CSV ファイル) は S3 に保存される. AWS コンソールからこれを確認しよう.

S3 のコンソールに行くと simplebatch-bucketXXXX (XXXX の部分はユーザーによって異なる) という名前のバケットが見つかるはずである. これをクリックして中身を見てみると, metrics_lr0.0100_m0.1000.csv という名前の CSV があることが確認できるだろう (figure_title). これが, 学習率 = 0.01, モメンタム = 0.1 として学習を行ったときの結果である.

ジョブの実行結果は S3 に保存される

さて,ここで run_single.ipynb に戻ってこよう. [5] から [7] 番のセルでは,学習結果の CSV ファイルのダウンロードを行っている.

python
# [5]
import pandas as pd
import io
from matplotlib import pyplot as plt

# [6]
def read_table_from_s3(bucket_name, key, profile_name=None):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    s3 = session.resource("s3")
    bucket = s3.Bucket(bucket_name)

    obj = bucket.Object(key).get().get("Body")
    df = pd.read_csv(obj)

    return df

# [7]
bucket_name = "simplebatch-bucket43879c71-mbqaltx441fu"
df = read_table_from_s3(
    bucket_name,
    "metrics_lr0.0100_m0.1000.csv"
)
# [5]
import pandas as pd
import io
from matplotlib import pyplot as plt

# [6]
def read_table_from_s3(bucket_name, key, profile_name=None):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    s3 = session.resource("s3")
    bucket = s3.Bucket(bucket_name)

    obj = bucket.Object(key).get().get("Body")
    df = pd.read_csv(obj)

    return df

# [7]
bucket_name = "simplebatch-bucket43879c71-mbqaltx441fu"
df = read_table_from_s3(
    bucket_name,
    "metrics_lr0.0100_m0.1000.csv"
)

[6] で S3 から CSV データをダウンロードし, pandas の DataFrame オブジェクトとしてロードする関数を定義している. [7] を実行する際, bucket_name という変数の値を,自分自身のバケットの名前に置き換えることに注意しよう (先ほど S3 コンソールから確認した simplebatch-bucketXXXX のことである).

続いて, [9] 番のセルで, CSV のデータをプロットしている (figure_title). ローカルで実行したときと同じように, AWS Batch を用いて MNIST モデルを訓練することに成功した!

python
# [9]
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(9,4))
x = [i for i in range(df.shape[0])]
ax1.plot(x, df["train_loss"], label="Train")
ax1.plot(x, df["val_loss"], label="Val")
ax2.plot(x, df["val_accuracy"])

ax1.set_xlabel("Epochs")
ax1.set_ylabel("Loss")
ax1.legend()

ax2.set_xlabel("Epochs")
ax2.set_ylabel("Accuracy")

print("Best loss:", df["val_loss"].min())
print("Best loss epoch:", df["val_loss"].argmin())
print("Best accuracy:", df["val_accuracy"].max())
print("Best accuracy epoch:", df["val_accuracy"].argmax())
# [9]
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(9,4))
x = [i for i in range(df.shape[0])]
ax1.plot(x, df["train_loss"], label="Train")
ax1.plot(x, df["val_loss"], label="Val")
ax2.plot(x, df["val_accuracy"])

ax1.set_xlabel("Epochs")
ax1.set_ylabel("Loss")
ax1.legend()

ax2.set_xlabel("Epochs")
ax2.set_ylabel("Accuracy")

print("Best loss:", df["val_loss"].min())
print("Best loss epoch:", df["val_loss"].argmin())
print("Best accuracy:", df["val_accuracy"].max())
print("Best accuracy epoch:", df["val_accuracy"].argmax())

AWS Batch で行った MNIST モデルの学習の結果

並列に複数の Job を実行する

さて,ここからが最後の仕上げである. ここまでのハンズオンで構築した AWS Batch のシステムを使って,ハイパーパラメータサーチを実際に行おう.

先ほど実行した run_single.ipynb と同じディレクトリにある run_sweep.ipynb を開く.

セル [1], [2], [3] は run_single.ipynb と同一である.

python
# [1]
import boto3
import argparse

# [2]
# AWS 認証ヘルパー ...省略...

# [3]
def submit_job(lr:float, momentum:float, epochs:int, profile_name=None):
    # ...省略...
# [1]
import boto3
import argparse

# [2]
# AWS 認証ヘルパー ...省略...

# [3]
def submit_job(lr:float, momentum:float, epochs:int, profile_name=None):
    # ...省略...

セル [4] の for ループを使って,グリッド状にハイパーパラメータの組み合わせを用意し, batch にジョブを投入している. ここでは 3x3=9 個のジョブを作成した.

python
# [4]
for lr in [0.1, 0.01, 0.001]:
    for m in [0.5, 0.1, 0.05]:
        submit_job(lr, m, 100)
# [4]
for lr in [0.1, 0.01, 0.001]:
    for m in [0.5, 0.1, 0.05]:
        submit_job(lr, m, 100)

セル [4] を実行したら, Batch のコンソールを開こう. 先ほどと同様に,ジョブのステータスは SUBMITTED > RUNNABLE > STARTING > RUNNING と移り変わっていくことがわかるだろう. 最終的に 9 個のジョブがすべて RUNNING の状態になることを確認しよう (figure_title). また,このとき Compute environment の Desired vCPUs は 4x9=36 となっていることを確認しよう (figure_title).

複数のジョブを同時投入したときの Batch コンソール

次に,Batch のコンソールの左側のメニューから Jobs をクリックしてみよう. ここでは,実行中のジョブの一覧が確認することができる (figure_title). ジョブのステータスでフィルタリングをすることも可能である. 9 個のジョブがどれも RUNNING 状態にあることが確認できるだろう.

複数のジョブを同時投入したときの Job 一覧

今度は EC2 コンソールを見てみよう. 左のメニューから Instances を選択すると, figure_title に示すような起動中のインスタンスの一覧が表示される. g4dn.xlarge が 9 台稼働しているのが確認できる. Batch がジョブの投下に合わせて必要な数のインスタンスを起動してくれたのだ!

複数のジョブを同時投入したときの EC2 インスタンスの一覧

ここまで確認できたら,それぞれの Job が終了するまでしばらく待とう (だいたい 10-15 分くらいで終わる). すべてのジョブが終了すると,ダッシュボードの SUCCEEDED が 9 となっているはずだ. また, Compute environment の Desired vCPUs も 0 に落ちていることを確認しよう. 最後に EC2 コンソールに行って,すべての g4dn インスタンスが停止していることを確認しよう.

以上から, AWS Batch を使うことで,ジョブの投入に応じて自動的に EC2 インスタンスが起動され,ジョブの完了とともに,ただちにインスタンスの停止が行われる一連の挙動を観察することができた. 一つのジョブの完了におよそ 10 分の時間がかかるので,9 個のハイパーパラメータの組を逐次的に計算していた場合は 90 分の時間を要することになる. AWS Batch を使ってこれらの計算を並列に実行することで,ジョブ一個分の計算時間 (=10 分) ですべての計算を終えることができた!

さて,再び run_sweep.ipynb に戻ってこよう. [5] 以降のセルでは,グリッドサーチの結果を可視化している.

python
# [5]
import pandas as pd
import numpy as np
import io
from matplotlib import pyplot as plt

# [6]
def read_table_from_s3(bucket_name, key, profile_name=None):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    s3 = session.resource("s3")
    bucket = s3.Bucket(bucket_name)

    obj = bucket.Object(key).get().get("Body")
    df = pd.read_csv(obj)

    return df

# [7]
grid = np.zeros((3,3))
for (i, lr) in enumerate([0.1, 0.01, 0.001]):
    for (j, m) in enumerate([0.5, 0.1, 0.05]):
        key = f"metrics_lr{lr:0.4f}_m{m:0.4f}.csv"
        df = read_table_from_s3("simplebatch-bucket43879c71-mbqaltx441fu", key)
        grid[i,j] = df["val_accuracy"].max()

# [8]
fig, ax = plt.subplots(figsize=(6,6))
ax.set_aspect('equal')

c = ax.pcolor(grid, edgecolors='w', linewidths=2)

for i in range(3):
    for j in range(3):
        text = ax.text(j+0.5, i+0.5, f"{grid[i, j]:0.1f}",
                       ha="center", va="center", color="w")
# [5]
import pandas as pd
import numpy as np
import io
from matplotlib import pyplot as plt

# [6]
def read_table_from_s3(bucket_name, key, profile_name=None):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    s3 = session.resource("s3")
    bucket = s3.Bucket(bucket_name)

    obj = bucket.Object(key).get().get("Body")
    df = pd.read_csv(obj)

    return df

# [7]
grid = np.zeros((3,3))
for (i, lr) in enumerate([0.1, 0.01, 0.001]):
    for (j, m) in enumerate([0.5, 0.1, 0.05]):
        key = f"metrics_lr{lr:0.4f}_m{m:0.4f}.csv"
        df = read_table_from_s3("simplebatch-bucket43879c71-mbqaltx441fu", key)
        grid[i,j] = df["val_accuracy"].max()

# [8]
fig, ax = plt.subplots(figsize=(6,6))
ax.set_aspect('equal')

c = ax.pcolor(grid, edgecolors='w', linewidths=2)

for i in range(3):
    for j in range(3):
        text = ax.text(j+0.5, i+0.5, f"{grid[i, j]:0.1f}",
                       ha="center", va="center", color="w")

最終的に出力されるプロットが figure_title である.

ハイパーパラメータのグリッドサーチの結果

このプロットから,差は僅かであるが,学習率が 0.1 のときに精度は最大となることがわかる. また,学習率 0.1 のときはモメンタムを変えても大きな差は生じないことが見て取れる.

今回のパラメータサーチは勉強用に極めて単純化されたものである点は承知いただきたい.

たとえば,今回は学習率が 0.1 が最も良いとされたが,それは訓練のエポックを 100 に限定しているからかもしれない. 学習率が低いとその分訓練に必要なエポック数も多くなる. 訓練のエポック数をもっと増やせばまた違った結果が観察される可能性はある.

また,今回は MNIST の訓練データ 60,000 枚のうち, 48,000 枚を訓練データ,残り 12,000 枚を検証データとして用いた. この分割は乱数を固定してランダムに行ったが,もしこの分割によるデータのバイアスを気にするならば, k 個の異なる学習・検証データの分割をあらかじめ用意して,複数回モデルの評価を行う (k-fold cross-validation) 方法も,より精緻なアプローチとして考えられる.

以上のようにして, CNN を用いた MNIST 分類モデルのハイパーパラメータの最適化の一連の流れを体験した. AWS Batch を利用することで,比較的少ないプログラミングで,動的に EC2 クラスターを制御し,並列にジョブを処理するシステムが構築できた. ここまで EC2 を使いこなすことができれば,多くの問題を自力で解くことが可能になるだろう!

スタックの削除

これにて,本ハンズオンは終了である.最後にスタックを削除しよう. 今回のスタックを削除するにあたり,ECR に配置された Docker のイメージは手動で削除されなければならない (これをしないと, cdk destroy を実行したときにエラーになってしまう. これは CloudFormation の仕様なので従うしかない).

ECR の Docker image を削除するには, ECR のコンソールに行き,イメージが配置されたレポジトリを開く. そして,画面右上の DELETE ボタンを押して削除する (figure_title).

ECR から Docker image を削除する

あるいは, AWS CLI から同様の操作を行うには,以下のコマンドを用いる (XXXX は自分の ECR レポジトリ名に置き換える).

sh
$ aws ecr batch-delete-image --repository-name XXXX --image-ids imageTag=latest
$ aws ecr batch-delete-image --repository-name XXXX --image-ids imageTag=latest

image の削除が完了したうえで,次のコマンドでスタックを削除する.

sh
$ cdk destroy
$ cdk destroy

(#sec:batch_development_and_debug) === クラウドを用いた機械学習アプリケーションの開発とデバッグ

本章で紹介したハンズオンでは, AWS Batch を使用することでニューラルネットの学習を複数並列に実行し,高速化を実現した. 本章の最後の話題として,クラウドを用いた機械学習アプリケーションの開発とデバッグの方法について述べよう.

ローカルに GPU を搭載した強力なマシンがなく,クラウドを利用する予算が確保されているのであれば, figure_title のような開発のスキームが理想的であると考える. 最初の段階では, Hands-on #2: AWS でディープラーニングを実践 で見たような方法で, GPU 搭載型の EC2 インスタンスを作成し, Jupyter Notebook などのインタラクティブな環境で様々なモデルを試し実験を行う. Jupyter である程度アプリケーションが完成してきたタイミングで,作成したアプリケーションを Docker イメージにパッケージングする. そして, EC2 上で docker run を行い,作成したイメージがバグなく動作するか確認を行う. その次に,ハイパーパラメータの最適化などのチューニングを, Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する のハンズオンで学んだ AWS Batch などの計算システムを利用して行う. よい深層学習モデルが完成したら,仕上げに大規模データへの推論処理を行うシステムを Hands-on #3: AWS で自動質問回答ボットを走らせる を参考に構築する.

実際,本書ではこの流れに沿って演習を進めてきた. MNIST タスクを解くモデルを,最初 Jupyter Notebook を使用して実験し,そのコードをほとんどそのまま Docker にパッケージし, AWS Batch を用いてハイパーパラメータサーチを行った. このサイクルを繰り返すことで,クラウドを最大限に活用した機械学習アプリケーションの開発を進めることができる.

クラウドを活用した機械学習アプリケーションの開発フロー

小括

ここまでが,本書第二部の内容である. 第一部に引き続き盛りだくさんの内容であったが,ついてこれたであろうか?

第二部ではまず最初に,深層学習の計算をクラウドで実行するため, GPU 搭載型の EC2 インスタンスの起動について解説した. さらに,ハンズオンでは,クラウドに起動した仮想サーバーを使って MNIST 文字認識タスクを解くニューラルネットを訓練した (Hands-on #2: AWS でディープラーニングを実践).

また,より大規模な機械学習アプリケーションを作るための手段として, Docker と ECS によるクラスターの初歩を説明した (Docker 入門). その応用として,英語で与えられた文章問題への回答を自動で生成するボットをクラウドに展開した (Hands-on #3: AWS で自動質問回答ボットを走らせる). タスクの投入に応じて動的に計算リソースが作成・削除される様子を実際に体験できただろう.

さらに, Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する では AWS Batch を用いてニューラルネットの学習を並列に実行する方法を紹介した. ここで紹介した方法は,ミニマムであるが,計算機システムを大規模化していくためのエッセンスが網羅されている. これらのハンズオン体験から,クラウド技術を応用してどのように現実世界の問題を解いていくのか,なんとなくイメージが伝わっただろうか?

本書の第三部では,さらにレベルアップし,サーバーレスアーキテクチャという最新のクラウドの設計手法について解説する. その応用として,ハンズオンでは簡単な SNS サービスをゼロから実装する. 引き続きクラウドの最先端の世界を楽しんでいこう!

Web サービスの作り方

ここからが,本書第三部の内容になる. これまでのセクションでは,仮想サーバーをクラウド上に起動し,そこで計算を走らせる方法について解説をしてきた. EC2, ECS, Fargate, Batch などを利用して,動的にスケールするクラスターを構成し,並列にタスクを実行するクラウドシステムを実装してきた. 振り返ると,これまで紹介してきた内容は,自分自身が行いたい計算をクラウドを駆使することで実現する,という用途にフォーカスしていたことに気がつくだろう. 一方で,広く一般の人々に使ってもらえるような計算サービス・データベースを提供する,というのもクラウドの重要な役割として挙げられる.

本章から始まる第三部では,前回までとは少し方向性を変え,どのようにしてクラウド上にアプリケーションを展開し,広く一般の人に使ってもらうか,という点を講義したいと思う. これを通じて,どのようにして世の中のウェブサービスができ上がっているのかを知り,さらにどうやって自分でそのようなアプリケーションをゼロから構築するのか,という点を学んでもらう. その過程で,サーバーレスアーキテクチャという最新のクラウド設計手法を解説する.

その前準備として,本章ではどのようにしてウェブサービスが出来上がっているのか,その背後にある技術の概要を解説する. 用語の解説が中心となるが,後のハンズオンを実装するために必須の知識であるので,理解して前に進むよう心がけよう.

ウェブサービスの仕組み  — Twitter を例に

あなたがパソコンやスマートフォンから Twitter, Facebook, YouTube などのウェブサービスにアクセスしたとき,実際にどのようなことが行われ,コンテンツが提示されているのだろうか?

HTTP を通じたサーバーとクライアントのデータのやり取りは,すでに知っている読者も多いだろうし,逆にすべて解説しようとすると紙面が足りないので,ここではエッセンスの説明のみにとどめる. 以降では Twitter を具体例として,背後にあるサーバーとクライアントの間の通信を概説しよう. 概念図としては figure_title のような通信がクライアントとサーバーの間で行われていることになる.

クライアントと Web サーバーの通信の概念図

前提として,クライアントとサーバーの通信は HTTP (Hypertext Transfer Protocol) を使って行われる. また,最近では,暗号化された HTTP である HTTPS (HTTPS (Hypertext Transfer Protocol Secure)) を用いることがスタンダードになってきている. 第一のステップとして,クライアントは HTTP(S) 通信によってサーバーから静的なコンテンツを取得する. 静的なコンテンツとは, HTML (Hyptertext Markup Language) で記述されたウェブページの文書本体, CSS (Cascading Style Sheets) で記述されたページのデザインやレイアウトファイル,そして JavaScript (JS) で記述されたページの動的な挙動を定義したプログラム,が含まれる. Twitter を含む現代的なウェブアプリケーションの設計では,この静的なファイル群はページの”枠”を定義するだけで,中身となるコンテンツ (例: ツイートの一覧) は別途 API (Application Programming Interface) によって取得されなければならない. そこで,クライアントは先のステップで取得された JavaScript で定義されたプログラムに従って,サーバーに API を送信し,ツイートや画像データを取得する. この際,テキストデータのやり取りには JSON (JavaScript Object Notation) というフォーマットが用いられることが多い. 画像や動画などのコンテンツも同様に API により取得される. このようにして取得されたテキストや画像が,HTML の文書に埋め込まれることで,最終的にユーザーに提示されるページが完成するのである. また,新しいツイートを投稿するときにも,クライアントから API を通じてサーバーのデータベースにデータが書き込まれる.

REST API

API (Application Programming Interface) とはこれまで何度も出てきた言葉であるが,ここではよりフォーマルな定義付けを行う. API とはあるソフトウェア・アプリケーションが,外部のソフトウェアに対してコマンドやデータをやり取りするための媒介の一般的総称である. とくに,ウェブサービスの文脈では,サーバーが外界に対して提示しているコマンドの一覧のことを意味する. クライアントは,提示されている API から適切なコマンドを使うことによって,所望のデータを取得したり,あるいはサーバーにデータを送信したりする.

とくに,ウェブの文脈では REST (Representational State Transfer) とよばれる設計思想に基づいた API が現在では最も一般的に使われている. REST の設計指針に従った API のことを REST API あるいは RESTful API とよんだりする.

REST API は, figure_title に示したような MethodURI (Universal Resource Identifier) の組からなる.

REST API

Method (メソッド) とは,どのような操作を行いたいかを抽象的に表す,"動詞" として捉えることができる. メソッドには HTTP 規格で定義された 9 個の動詞 (verb) を使用することができる. この中でも, GET, POST, PUT, PATCH, DELETE の 5 個が最も頻繁に使用される (table_title). この 5 つのメソッドによる操作を総称して CRUD (create, read, update, and delete) とよぶ.

REST API Methods
メソッド意図される動作

GET

要素を取得する

POST

新しい要素を作成する

PUT

既存の要素を新しい要素と置き換える

PATCH

既存の要素の一部を更新する

DELETE

要素を削除する

一方, URI は操作が行われる対象,すなわち "目的語" を表す. ウェブの文脈では操作が行われる対象のことをしばしば リソース とよぶ. URI は多くの場合 http または https から始まるウェブサーバーのアドレスから始まり, / (スラッシュ) 以降に所望のリソースのパスが指定される. figure_title の例で言えば, https://api.twitter.com というアドレスの /1.1/status/home_timeline というリソースを取得 (GET) せよ,という意味になる (なお,ここで 1.1 という数字は API のバージョンを示している). この API リクエストによって,ユーザーのホームのタイムラインのツイートの一覧が取得される.

REST API のメソッドには, table_title で挙げたもの以外に, HTTP プロトコルで定義されているほかのメソッド (OPTIONS, TRACE など) を用いることもできるが,あまり一般的ではない.

また,これらのメソッドだけでは動詞として表現しきれないこともあるが, URI の名前でより意味を明確にすることもある. メソッドの使い方も,要素を削除する際は必ず DELETE を使わなければならない,という決まりもなく,たとえば, Twitter API でツイートを消す API は POST statuses/destroy/:id で定義されている. 最終的には,各ウェブサービスが公開している API ドキュメンテーションを読んで,それぞれの API がどんな操作をするのかを調べる必要がある.

REST の概念は 2000 年代初頭に確立され,今日の API 設計のスタンダードとなった. 一方で,ウェブのテクノロジーが進歩するにつれて,新たな API の設計アプローチの需要も高まっている. 近年とくに人気を集めているのが, GraphQL と呼ばれる API の設計方法である. GraphQL は Facebook 社によって最初に作られ,現在は GraghQL Foundation によって維持と更新がされている. GraphQL を使用すると,クライアントは REST と比較してより柔軟性の高いデータのクエリを行うことができるなど,いくつかの利点がある. キーワードだけでも知っておくと,今後役に立つだろう.

Twitter API

もう少し具体的にウェブサービスの API を体験する目的で,ここでは Twitter の API を見てみよう. Twitter が提供している API の一覧は Twitter の Developer Documentation で見ることができる. いくつかの代表的な API を table_title にまとめた.

Twitter API
エンドポイント動作

GET statuses/home_timeline

ホームのタイムラインのツイートの一覧を取得する.

GET statuses/show/:id

:id で指定されたツイートの詳細情報を取得する.

GET search

ツイートの検索を実行する.

POST statuses/update

新しいツイートを投稿する.

POST media/upload

画像をアップロードする

POST statuses/destroy/:id

:id で指定されたツイートを削除する.

POST statuses/retweet/:id

:id で指定されたツイートをリツイートする.

POST statuses/unretweet/:id

:id で指定されたツイートのリツイートを取り消す.

POST favorites/create

選択したツイートを"いいね"する.

POST favorites/destroy

選択したツイートを"いいね"を取り消す.

この API リストをもとに, Twitter のアプリまたはウェブサイトを開いたときに起こるクライアントとサーバーの通信をシミュレートしてみよう.

ユーザーが Twitter を開くと,まず最初に GET statuses/home_timeline の API リクエストによって,ユーザーのホームのタイムラインのツイートのリストが取得される. 個々のツイートは JSON 形式のデータになっており, id, text, user, coordinates, entities などの属性を含む. id はツイートに固有な ID を表し, text はツイートの本文を含んでいる. user はツイートを投稿したユーザーの名前やプロフィール画像の URL などを含んだ JSON データになっている. coordinates にはツイートが発信された地理的な座標が記録されている. また, entities にはツイートに関連するメディアファイル (画像など) のリンクなどの情報が埋め込まれている. GET statuses/home_timeline からは直近のツイートのリスト (リストが長すぎる場合は途中で切られたもの) が取得される. もしツイートの ID を知っている場合は GET statuses/show/:id を呼ぶことによって, :id パラメータで指定された特定のツイートを取得することができる.

ツイートの検索を行うためには GET search API を使用する. この API には,ツイートに含まれる単語や,ハッシュタグ,ツイートの発信された日時や場所など,様々なクエリの条件を渡すことができる. API からは, GET statuses/home_timeline などと同様, JSON 形式のツイートのデータが返される.

ユーザーが新しいツイートを投稿するには POST statuses/update のエンドポイントを利用する. POST statuses/update には,ツイートの文章や,リプライの場合はリプライ先のツイートの ID などのデータを送信する. また,ツイートに画像データを添付したい場合は, POST media/upload を併せて使用する. ツイートの削除を行うには, POST statuses/destroy/:id を用いる.

そのほか,頻繁に行われる操作としては, POST statuses/retweet/:idPOST statuses/unretweet/:id がある. これらは, :id で指定されるツイートに対して,それぞれリツイートを実行あるいは取り消すための API である. また, POST favorites/createPOST favorites/destroy を使用することによって,選択されたツイートに"いいね"を追加したり,取り消したりする操作を行う.

このような一連の操作が, Twitter のアプリの背後では行われている. また,自分自身でボットを作成したい場合は,これらの API を適切に組み合わせ,カスタムのプログラムを書くことで実現される.

このように, API はあらゆるウェブサービスを作るうえで一番基礎となる要素である. 次からの章では本章で紹介した用語が何度も出てくるので,頭の片隅に置いたうえで読み進めていただきたい.

Serverless architecture

サーバーレスアーキテクチャ (Serverless architecture) あるいは サーバーレスコンピューティング (Serverless computing) とは,従来とは全く異なるアプローチに基づくクラウドシステムの設計方法である. 歴史的には, AWS が 2014 年に発表した Lamba がサーバーレスアーキテクチャの先駆けとされている. その後, Google や Microsoft などのクラウドプラットフォームも同様の機能の提供を開始している. サーバーレスアーキテクチャの利点は,スケーラブルなクラウドシステムを安価かつ簡易に作成できる点であり,近年いたるところで導入が進んでいる.

Serverless とは,文字どおりの意味としてはサーバーなしで計算をするということになるが,それは一体どういう意味だろうか? サーバーレスについて説明するためには,まずは従来的な, "serverful" とよばれるようなシステムについて解説しなければならない.

Serverful クラウド (従来型)

従来的なクラウドシステムのスケッチを figure_title に示す. クライアントから送信されたリクエストは,最初に API サーバーに送られる. API サーバーでは,リクエストの内容に応じてタスクが実行される. タスクには,API サーバーだけで完結できるものもあるが,多くの場合,データベースの読み書きが必要である. データベースには,データベース専用の独立したサーバーマシンが用いられることが一般的である. また,画像や動画などの容量の大きいデータは,また別のストレージサーバーに保存されることが多い. これらの API サーバー,データベースサーバー,ストレージサーバーはそれぞれ独立したサーバーマシンであり, AWS の言葉では EC2 による仮想インスタンスを想定してもらったらよい.

多くのウェブサービスでは,多数のクライアントからのリクエストを処理するため,複数のサーバーマシンがクラウド内で起動し,負荷を分散するような設計がなされている. クライアントから来たリクエストを計算容量に余裕のあるサーバーに振り分けるような操作を Load balancing とよび,そのような操作を担当するマシンのことを Load balancer という.

計算負荷を分散する目的で多数のインスタンスを起動するのはよいのだが,計算負荷が小さすぎてアイドリング状態にあるようではコストと電力の無駄遣いである. したがって,すべてのサーバーが常に目標とする計算負荷を維持するよう,計算の負荷に応じてクラスター内の仮想サーバーの数を動的に増減させるような仕組みが必要である. そのような仕組みをクラスターのスケーリングとよび,負荷の増大に応答して新しい仮想インスタンスをクラスターに追加する操作を scale-out,負荷の減少に応答してインスタンスをシャットダウンする操作を scale-in とよぶ. クラスターのスケーリングは, API サーバーではもちろんのこと,データベースサーバー・ストレージサーバーでも必要になる. ストレージサーバーでは,例えば頻繁にアクセスされるデータはキャッシュ領域に保存したり,データのコピーを複数作るなどのスケーリングが行われる. データベースサーバーも同様に,頻繁にアクセスされるデータのアクセスがパンクしてしまわないよう,分散的な処理が必要となる. このように,クラウドシステム内すべての箇所で,負荷が均一になるような調整が必要であり,開発者は多くの時間をそのチューニングに費やさなければならない. また,サービスの利用者の数などに応じてスケーリングの設定は常に見直される必要があり,継続的な開発が要求される.

さらに問題を複雑にするのは,API サーバーで処理されるべきタスクが,非一様な点である. 非一様であるとは,たとえばタスク A は 3000 ミリ秒の実行時間と 512MB のメモリーを消費し,別のタスク B は 1000 ミリ秒の実行時間と 128MB のメモリーを消費する,というような状況を指している. 一つのサーバーマシンが計算負荷が異なる複数のタスクを処理する場合,クラスターのスケーリングはより複雑になる. この状況をシンプルにするために,1サーバーで実行するタスクは1種類に限る,という設計も可能であるが,そうするとで生まれる弊害も多い (ほとんど使われないタスクに対してもサーバー一台をまるまる割り当てなければならない = ほとんどアイドリング状態になってしまう,など).

Serverful なクラウドシステム

Serverless クラウドへ

Serverful クラウド (従来型) で議論したように,クラスターのスケーリングはクラウドシステムの経済的効率とシステムの安定性を最大化するために必須の作業である. それを反映して,多くの開発者の時間が投資されてきた.

クラスターのスケーリングはすべての開発者が何度も繰り返し行ってきた作業であり,いくつかの側面をテンプレート化し,共通化することができたならば開発のコストを大幅に削減できるだろう. それを実現するには,根本的なレベルからクラウドシステムの設計を考え直す必要がある. スケーリングを前提として考えることで,もっとシンプルで見通しがよいクラウドシステムの設計の仕組みはないだろうか? そのような動機が,サーバーレスアーキテクチャが誕生する背後にあった.

従来の serverful なシステムでの最大の問題点は,サーバーをまるまる占有してしまうという点にある. すなわち, EC2 インスタンスを起動したとき,そのインスタンスは起動したユーザーだけが使えるものであり,計算のリソース (CPU や RAM) が独占的に割り当てられた状態になる. 固定した計算資源の割り当てがされてしまっているので,インスタンスの計算負荷が 0%であろうが 100%であろうが,均一の使用料金が起動時間に比例して発生する.

サーバーレスアーキテクチャは,このような 独占的に割り当てられた計算リソースというものを完全に廃止することを出発点とする. サーバーレスアーキテクチャでは,計算のリソースは,クラウドプロバイダーがすべて管理する. クライアントは,仮想インスタンスを一台まるごと借りるのではなく,計算のタスクの需要が生まれる毎に,実行したいプログラム・コマンドをクラウドに提出する. クラウドプロバイダーは,自身のもつ巨大な計算リソースから空きを探し,提出されたプログラムを実行し,実行結果をクライアントに返す. 言い換えると,計算リソースのスケーリングやアロケーションなどはクラウドプロバイダーが一手に引き受け,ユーザーはジョブをサブミットすることに注力する,という枠組みである. これを図示すると, figure_title のようになる.

従来のクラウドと Serverless クラウドの比較

サーバーレスクラウドでは,スケーリングはすべてクラウドプロバイダーが引き受けるので,スケーラビリティーが保証されている. クライアントが同時に大量のタスクを送信した場合でも,クラウドプロバイダー側の独自の仕組みによってすべてのタスクが遅延なく実行される. また,サーバーレスクラウドを利用することで,クラウドのコストは実際に使用した計算の総量 (稼働時間) で決定されることになる. これは,計算の実行総量に関わらずインスタンスの起動時間で料金が決定されていた従来のシステムと比べて大きな違いである.

サーバーレスクラウドは,従来のクラウドとは根本から異なったアプローチなので,コードの書き方やシステムの設計が大きく異なる. サーバーレスクラウドを開発・運用するには,サーバーレス固有の概念や用語に精通している必要がある. 以降では,実際にクラウドを動かしながら,サーバーレスをより具体的に体験していこう.

従来型の(仮想インスタンスをたくさん起動するような)クラウドシステムは,賃貸と似ているかもしれない. 部屋を借りるというのは,その部屋でどれだけの時間を過ごそうが,月々の家賃は一定である. 同様に,仮想サーバーも,それがどれほどの計算を行っているかに関わらず,一定の料金が時間ごとに発生する.

一方で,サーバーレスクラウドは,電気・水道・ガス料金 と似ている. こちらは,実際に使用した量に比例して料金が決定されている. サーバーレスクラウドも,実際に計算を行った総時間で料金が決まる仕組みになっている.

サーバーレスクラウドを構成するコンポーネント

サーバーレスアーキテクチャの概要がわかってきたところで,ここでは AWS においてサーバーレスクラウドを構成する様々なコンポーネントを紹介していこう. 特に, Lambda, S3, DynamoDB を取り上げ,解説する (figure_title). サーバーレスクラウドは,これらのコンポーネントを統合することで一つのシステムが出来上がる. ここでは, Lambda,S3,DynamoDB を利用する際に押さえておかなければならない知識を一通り説明しきる都合上,具体的なイメージがわきにくいかもしれない. が,続く Hands-on #5: サーバーレス入門 でそれぞれについてハンズオン形式で演習を行うので,そこでさらに理解を深めれば大丈夫である.

Lambda, S3, DynamoDB のアイコン

Lambda

AWS でサーバーレスコンピューティングの中心を担うのが, Lambda である. Lambda の使い方を figure_title に図示している. Lambda の仕組みはシンプルで,まずユーザーは実行したいプログラムのコードを事前に登録しておく. プログラムは, Python, Node.js, Ruby などの主要な言語がサポートされている. Lambda に登録されたひとつひとつのプログラムを関数 (Function) とよぶ. そして,関数を実行したいときに,invoke コマンドを Lambda に送信する. Lambda では, invoke のリクエストを受け取るとただちに (数ミリセカンドから数百ミリセカンド程度の時間で) プログラムの実行を開始する. そして,実行結果をクライアントやその他の計算機に返す.

AWS Lambda

このように,Lambda では占有された仮想インスタンスは存在せず,実行を待っているプログラムだけがある状態である. invoke のリクエストに応じて,プログラムが AWS の巨大な計算機プールのどこかに配置され,実行される. 同時に複数のリクエストが来た場合でも, AWS はそれらを実行するための計算リソースを割り当て,並列的に処理を行ってくれる. 原理上は,数千から数万のリクエストが同時に来たとしても, Lambda はそれらを同時に実行することができる. このような,占有された仮想サーバーの存在なしに,動的に関数を実行するサービスのことを総称して FaaS (Function as a Service) とよぶ.

Lambda ではそれぞれの関数につき, 128MB から 10240MB のメモリーを使用することができる (執筆時点の仕様). また,実効的な CPU のパワーはメモリーの量に比例する形で割り当てられる. すなわち,タスクに割り当てたメモリーの量が多ければ多いほど,より多くの CPU リソースが割り当てられることになる (しかし, RAM と CPU パワーの具体的な換算表は AWS からは公開されていない). 実行時間は 100 ミリ秒の単位で記録され,実行時間に比例して料金が決定される. table_title は Lambda の利用料金表である (執筆時点で ap-north-east1 リージョンを選択した場合).

Lambda の料金表
Memory (MB)Price per 100ms

128

$0.0000002083

512

$0.0000008333

1024

$0.0000016667

3008

$0.0000048958

実行時間に比例する料金に追加して,リクエストを送信するごとに発生する料金が設定されている. これは,百万回のリクエストにつき $0.2 である. たとえば, 128MB のメモリーを使用する関数を,それぞれ 200 ミリ秒,合計で 100 万回実行した場合, 0.0000002083 * 2 * 10^6 + 0.2 = $0.6 の料金となる. ウェブサーバーのデータベースの更新など簡単な計算であれば,200 ミリ秒程度で実行できる関数も多いことから,100 万回データベースの更新を行ったとしても,たった $0.6 しかコストが発生しないことになる. また,コードが実行されず待機状態になっている場合は,発生する料金は 0 である. このように,実際に意味のある処理が行われた時間にのみ,料金が発生する仕組みになっている.

Lambda は比較的短時間で完了する,反復性の高いタスクの実行に向いている. データベースの読み書きはその典型的な例であるが,そのほかにも,画像のサイズをトリミングしたり,サーバーサイドで定期的に実行されるメンテナンス処理などの利用が考えられる. また,複数の Lambda をリレー式に繋げることも可能で,シンプルな処理を組み合わせることで複雑なロジックを表現することができる.

上述の Lambda の料金計算は,説明のためコストに寄与する要素をいくつか省いている点は承知いただきたい. 例えば, DynamoDB の読み書きに関する料金や,ネットワークの通信にかかわるコストが考慮されていない.

サーバーレスストレージ: S3

サーバーレスの概念は,ストレージにも拡張されている.

従来的なストレージ (ファイルシステム) では,必ずホストとなるマシンと OS が存在しなければならない. したがって,それほどパワーは必要ないまでも,ある程度の CPU リソースを割かなければならない. また,従来的なファイルシステムでは,データ領域のサイズは最初にディスクを初期化するときに決めなければならず,後から容量を増加させることはしばしば困難である (ZFS などのファイルシステムを使えばある程度は自由にファイルシステムのサイズを変更することは可能である). よって,従来的なクラウドでは,ストレージを借りる際にはあらかじめディスクのサイズを指定せねばならず,ディスクの中身が空であろうと満杯であろうと,同じ利用料金が発生することになる (figure_title).

Simple Storage Service (S3) は,サーバーレスなストレージシステムを提供する (figure_title). S3 は従来的なストレージシステムと異なり, OS に"マウントする”という概念はない. 基本的に API を通じてデータの読み書きの操作が行われる. また,データの冗長化や暗号化,バックアップの作成など,通常ならば OS と CPU が介在しなければならない操作も, API を通じて行うことができる. S3 では事前に決められたディスク領域のサイズはなく,データを入れれば入れた分だけ,保存領域は拡大していく (仕様上はペタバイトスケールのデータを保存することが可能である). ストレージにかかる料金は,保存してあるデータの総容量で決定される.

S3 と従来的なファイルシステムの比較

S3 を利用する際に,料金に関わってくる主要な事項をまとめたのが table_title である (us-east-1 リージョンのもの. 説明のため主要な事項のみ取り出している. 詳細は 公式ドキュメンテーション "Amazon S3 pricing" を参照).

S3 の利用料金
項目料金

Data storage (First 50TB)

$0.023 per GB per month

PUT, COPY, POST, LIST requests (per 1,000 requests)

$0.005

GET, SELECT, and all other requests (per 1,000 requests)

$0.0004

Data Transfer IN To Amazon S3 From Internet

$0

Data Transfer OUT From Amazon S3 To Internet

$0.09 per GB

第一に,データの保存には $0.025 per GB のコストが月ごとに発生する. したがって,1000GB のデータを S3 に一ヵ月保存した場合, $25 の料金が発生することになる. また,PUT, COPY, POST などのリクエスト (=データを書き込む操作) に対しては,データ容量に関係なく,1000 回ごとに $0.005 のコストが発生する. GET, SELECT などのリクエスト (=データを読み込む操作) に対しては,1000 回ごとに $0.0004 のコストが発生する. また, S3 はデータを外に取り出す際の通信にもコストが生じる. 執筆時点では,S3 からインターネットを通じて外部にデータを転送 (data-out) すると $0.09 per GB のコストが発生する. データをインターネットを通じて S3 に入れる (data-in) 通信は無料で行える. また, AWS の 同じ Region 内のサービス (Lambda や EC2 など) にデータを転送するのは無料である. AWS のリージョンをまたいだデータの転送にはコストが発生する. いずれにせよ,サーバーレスの概念に則り,すべての料金が従量課金制で決定される設定になっている.

サーバーレスデータベース: DynamoDB

サーバーレスの概念は,データベースにも適用することができる.

ここでいうデータベースとは, Web サービスなどにおけるユーザーや商品の情報を記録しておくための保存領域のことを指している. 従来的に有名なデータベースとしては MySQL, PostgreSQL, MongoDB などが挙げられる. データベースと普通のストレージの違いは,データの検索機能にある. 普通のストレージではデータは単純にディスクに書き込まれるだけだが, データベースでは検索がより効率的になるようなデータの配置がされたり, 頻繁にアクセスされるデータはメモリーにキャッシュされるなどの機能が備わっている. これにより,巨大なデータの中から,興味のある要素を高速に取得することができる.

このような検索機能を実現するには,当然 CPU の存在が必須である. したがって,従来的なデータベースを構築する際は,ストレージ領域に加えて,たくさんの CPU コアを搭載したマシンが用いられることが多い. また,データベースが巨大な場合は複数マシンにまたがった分散型のシステムが設計される. 分散型システムの場合は, Serverful クラウド (従来型) で議論したようにデータベースへのアクセス負荷に応じて適切なスケーリングがなされる必要がある.

DynamoDB は, AWS が提供しているサーバーレスな分散型データベースである. サーバーレスであるので,占有されたデータベース用仮想インスタンスは存在せず, API を通じてデータの書き込み・読み出し・検索などの操作を行う. S3 と同様に,データ保存領域の上限は定められておらず,データを入れれば入れた分だけ,保存領域は拡大していく. また,データベースへの負荷が増減したときのスケーリングは, DynamoDB が自動で行うので,ユーザーは心配する必要はない.

DynamoDB での利用料金の計算はやや複雑なのだが, "On-demand Capacity" というモードで使用した場合の料金に関わってくる主要な事項をまとめたのが table_title である (us-east-1 リージョンのもの. 詳細は 公式ドキュメンテーション "Pricing for On-Demand Capacity" を参照).

DynamoDB の利用料金
項目料金

Write request units

$1.25 per million write request units

Read request units

$0.25 per million read request units

Data storage

$0.25 per GB-month

DynamoDB ではデータの書き込み操作の単位を write request unit とよび,データの読み込み操作の単位を read request unit とよぶ. 基本的に, 1kB 以下のデータを一度書き込むと 1 write request unit を消費し,4kB 以下のデータを一度読み込むと 1 read request unit を消費する (詳しくは 公式ドキュメンテーション "Read/Write Capacity Mode" を参照のこと). write request units は 100 万回ごとに $1.25, read request units は 100 万回ごとに $0.25 のコストが設定されている. また,保存されたデータ容量に対して $0.25 per GB のコストが月ごとに発生する. DynamoDB は高速な検索機能などを備えたデータベースであるので, GB あたりのストレージコストは S3 に比べ 10 倍程度高い. DynamoDB のデータの転送に関わるコストは,同じリージョン内ならば data-in,data-out ともに $0 である. リージョンをまたいだ通信には別途コストが発生する.

その他のサーバーレスクラウドの構成要素

以上で紹介した Lambda, S3, DynamoDB がサーバーレスクラウドの中で最も使用する頻度が高いサービスになる. その他のサーバーレスクラウドの構成要素を以下に列挙する. いくつかについては,今後のハンズオンを行う中で改めて解説を行う.

サーバーレスアーキテクチャは万能か?

この問いへの答えは,筆者は NO であると考える.

ここまで,サーバーレスの利点を強調して説明をしてきたが,まだまだ新しい技術なだけに,欠点,あるいはサーバーフルなシステムに劣る点は数多くある.

大きな欠点を一つあげるとすれば,サーバーレスのシステムは各クラウドプラットフォームに固有なものなので,特定のプラットフォームでしか運用できないシステムになってしまう点であろう. AWS で作成したサーバーレスのシステムを, Google のクラウドに移植するには,かなり大掛かりなプログラムの書き換えが必要になる. 一方, serverful なシステムであれば,プラットフォーム間のマイグレーションは比較的簡単に行うことができる. クラウドプロバイダーとしては,自社のシステムへの依存度を強めることで,顧客を離さないようにするという狙いがあるのだろう…

その他,サーバーレスコンピューティングの欠点や今後の課題などは,次の論文で詳しく議論されている. 興味のある読者はぜひ読んでいただきたい.

Hands-on #5: サーバーレス入門

前章ではサーバーレスアーキテクチャの概要の説明を行った. 本章では,ハンズオン形式でサーバーレスクラウドを実際に動かしながら,具体的な使用方法を学んでいこう. 今回のハンズオンでは Lambda, S3, DynamoDB の三つのサーバーレスクラウドの構成要素に触れていく. それぞれについて,短いチュートリアルを用意してある.

Lambda ハンズオン

まずは, Lambda を実際に動かしてみよう. ハンズオンのソースコードは GitHub の handson/serverless/lambda に置いてある.

このハンズオンで使用するアプリケーションのスケッチを figure_title に示す. STEP 1 では,AWS CDK を使用して Python で書かれたコードを Lambda に登録する. 続いて STEP 2 では, Invoke API を使用して,同時にいくつもの Lambda を起動し,並列な計算を行う. Lambda のワークフローを体験する目的で最小限の設定である.

Lambda チュートリアルの概要

このハンズオンは,基本的に AWS Lambda の無料枠 の範囲内で実行することができる.

app.py にデプロイするプログラムが書かれている. 中身を見てみよう.

py
#
FUNC = """
import time
from random import choice, randint
def handler(event, context):
    time.sleep(randint(2,5))
    sushi = ["salmon", "tuna", "squid"]
    message = "Welcome to Cloud Sushi. Your order is " + choice(sushi)
    print(message)
    return message
"""

class SimpleLambda(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        handler = _lambda.Function(
            self, 'LambdaHandler',
            runtime=_lambda.Runtime.PYTHON_3_7,
            code=_lambda.Code.from_inline(FUNC),
            handler="index.handler",
            memory_size=128,
            timeout=core.Duration.seconds(10),
            dead_letter_queue_enabled=True,
        )
#
FUNC = """
import time
from random import choice, randint
def handler(event, context):
    time.sleep(randint(2,5))
    sushi = ["salmon", "tuna", "squid"]
    message = "Welcome to Cloud Sushi. Your order is " + choice(sushi)
    print(message)
    return message
"""

class SimpleLambda(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        handler = _lambda.Function(
            self, 'LambdaHandler',
            runtime=_lambda.Runtime.PYTHON_3_7,
            code=_lambda.Code.from_inline(FUNC),
            handler="index.handler",
            memory_size=128,
            timeout=core.Duration.seconds(10),
            dead_letter_queue_enabled=True,
        )
  • ここで, Lambda で実行されるべき関数を定義している. これは非常に単純な関数で,2-5 秒のランダムな時間スリープした後,["salmon", "tuna", "squid"] のいずれかの文字列をランダムに選択し, "Welcome to Cloud Sushi. Your order is XXXX" (XXXX は選ばれた寿司のネタ) というメッセージをリターンする.

  • 次に, Lambda に <1> で書いた関数を配置している. パラメータの意味は,文字どおりの意味なので難しくはないが,以下に解説する.

    • runtime=_lambda.Runtime.PYTHON_3_7: ここでは, Python3.7 を使って上記で定義された関数を実行せよ,と指定している. Python3.7 のほかに, Node.js, Java, Ruby, Go などの言語を指定することが可能である.

    • code=_lambda.Code.from_inline(FUNC): 実行されるべき関数が書かれたコードを指定する. ここでは, FUNC=... で定義した文字列を渡しているが,文字列以外にもファイルのパスを渡すことも可能である.

    • handler="index.handler": これは,コードの中にいくつかのサブ関数が含まれているときに,メインとサブを区別するためのパラメータである. handler という名前の関数をメイン関数として実行せよ,という意味である.

    • memory_size=128: メモリーは 128MB を最大で使用することを指定している.

    • timeout=core.Duration.seconds(10) タイムアウト時間を 10 秒に設定している. 10 秒以内に関数の実行が終了しなかった場合,エラーが返される.

    • dead_letter_queue_enabled=True: アドバンストな設定なので説明は省略する.

上記のプログラムを実行することで, Lambda 関数がクラウド上に作成される. 早速デプロイしてみよう.

デプロイ

デプロイの手順は,これまでのハンズオンとほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). それぞれの意味を忘れてしまった場合は,ハンズオン 1, 2 に戻って復習していただきたい. シークレットキーの設定も忘れずに (AWS CLI のインストール).

sh
# プロジェクトのディレクトリに移動
$ cd handson/serverless/lambda

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd handson/serverless/lambda

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイのコマンドが無事に実行されれば, figure_title のような出力が得られるはずである. ここで表示されている SimpleLambda.FunctionName = XXXX の XXXX の文字列は後で使うのでメモしておこう.

CDKデプロイ実行後の出力

AWS コンソールにログインして,デプロイされたスタックを確認してみよう. コンソールから,Lambda のページに行くと figure_title のような画面から Lambda の関数の一覧が確認できる.

Lambda コンソール - 関数の一覧

今回のアプリケーションで作成したのが SimpleLambda で始まるランダムな名前のついた関数だ. 関数の名前をクリックして,詳細を見てみる. すると figure_title のような画面が表示されるはずだ. 先ほどプログラムの中で定義した Python の関数がエディターから確認できる. さらに下の方にスクロールすると,関数の各種設定も確認できる.

Lambda コンソール - 関数の詳細

Lambda で実行されるコードは, Lambda のコンソール画面 (figure_title) のエディターで編集することもできる. デバッグをするときなどは,こちらを直接いじる方が早い場合もある. その場合は, CDK のコードに行った編集を反映させなおすことを忘れずに.

Lambda 関数の実行

それでは,作成した Lambda 関数を実行 (invoke) してみよう. AWS の API を使うことで,関数の実行をスタートすることができる. 今回は, handson/serverless/lambda/invoke_one.py に関数を実行するための簡単なプログラムを提供している. 興味のある読者はコードを読んでもらいたい.

以下のコマンドで,Lambda の関数を実行する. コマンドの XXXX の部分は,先ほどデプロイしたときに SimpleLambda.FunctionName = XXXX で得られた XXXX の文字列で置換する.

sh
$ python invoke_one.py XXXX
$ python invoke_one.py XXXX

すると, "Welcome to Cloud Sushi. Your order is salmon" という出力が得られるはずだ. とてもシンプルではあるが,クラウド上で先ほどの関数が走り,乱数が生成されたうえで,ランダムな寿司ネタが選択されて出力が返されている. このコマンドを何度か打ってみて,実行ごとに異なる寿司ネタが返されることを確認しよう.

さて,このコマンドは,一度につき一回の関数を実行したわけであるが, Lambda の本領は一度に大量のタスクを同時に実行できる点である. そこで,今度は一度に 100 個のタスクを同時に送信してみよう. handson/serverless/lambda/invoke_many.py のスクリプトを使用する.

次のコマンドを実行しよう. XXXX の部分は前述と同様に置き換える. 第二引数の 100 は 100 個のタスクを投入せよ,という意味である.

sh
$ python invoke_many.py XXXX 100
$ python invoke_many.py XXXX 100

すると次のような出力が得られるはずだ.

sh
....................................................................................................
Submitted 100 tasks to Lambda!
....................................................................................................
Submitted 100 tasks to Lambda!

実際に,100 個のタスクが同時に実行されていることを確認しよう. figure_title の画面に戻り, "Monitoring" というタブがあるので,それをクリックする. すると, figure_title のようなグラフが表示されるだろう.

Lambda コンソール - 関数の実行のモニタリング

figure_title のグラフの更新には数分かかることがあるので,なにも表示されない場合は少し待つ.

figure_title で "Invocations" が関数が何度実行されたかを意味している. たしかに 100 回実行されていることがわかる. さらに, "Concurrent executions" は何個のタスクが同時に行われたかを示している. ここでは 96 となっていることから,96 個のタスクが並列的に実行されたことを意味している (これが 100 とならないのは,タスクの開始のコマンドが送られたのが完全には同タイミングではないことに起因する).

このように,非常にシンプルではあるが, Lambda を使うことで,同時並列的に処理を実行することのできるクラウドシステムを簡単に作ることができた.

もしこのようなことを従来的な serverful なクラウドで行おうとした場合,クラスターのスケーリングなど多くのコードを書くことに加えて,いろいろなパラメータを調節する必要がある.

興味がある人は,一気に 1000 個などのジョブを投入してみるとよい. Lambda はそのような大量のリクエストにも対応できることが確認できるだろう. が,あまりやりすぎると Lambda の無料利用枠を超えて料金が発生してしまうので注意.

スタックの削除

最後にスタックを削除しよう. スタックを削除するには,次のコマンドを実行すればよい.

sh
$ cdk destroy
$ cdk destroy

DynamoDB ハンズオン

続いて, DynamoDB の簡単なチュートリアルをやってみよう. ハンズオンのソースコードは GitHub の /handson/serverless/dynamodb に置いてある.

このハンズオンで使用するアプリケーションのスケッチを figure_title に示す. STEP 1 では,AWS CDK を使用して DynamoDB のテーブルを初期化し,デプロイする. 続いて STEP 2 では, API を使用してデータベースのデータの書き込み・読み出し・削除などの操作を練習する.

DynamoDB チュートリアルの概要

このハンズオンは,基本的に AWS DynamoDB の無料枠 の範囲内で実行できる.

handson/serverless/dynamodb/app.py にデプロイするプログラムが書かれている. 中身を見てみよう.

python
class SimpleDynamoDb(core.Stack):
    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        table = ddb.Table(
            self, "SimpleTable",
            #
            partition_key=ddb.Attribute(
                name="item_id",
                type=ddb.AttributeType.STRING
            ),
            #
            billing_mode=ddb.BillingMode.PAY_PER_REQUEST,
            #
            removal_policy=core.RemovalPolicy.DESTROY
        )
class SimpleDynamoDb(core.Stack):
    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        table = ddb.Table(
            self, "SimpleTable",
            #
            partition_key=ddb.Attribute(
                name="item_id",
                type=ddb.AttributeType.STRING
            ),
            #
            billing_mode=ddb.BillingMode.PAY_PER_REQUEST,
            #
            removal_policy=core.RemovalPolicy.DESTROY
        )

このコードで,最低限の設定がなされた空の DynamoDB テーブルが作成される. それぞれのパラメータの意味を簡単に解説しよう.

  • partition_key: すべての DynamoDB テーブルには Partition key が定義されていなければならない. Partition key とは,テーブル内の要素 (レコード) ごとに存在する固有の ID のことである. 同一の Partition key をもった要素がテーブルの中に二つ以上存在することはできない (注: Sort Key を使用している場合は除く.詳しくは 公式ドキュメンテーション "Core Components of Amazon DynamoDB" 参照). また, Partition key が定義されていない要素はテーブルの中に存在することはできない. ここでは, Partition key に item_id という名前をつけている.

  • billing_mode: ddb.BillingMode.PAY_PER_REQUEST を指定することで, On-demand Capacity Mode の DynamoDB が作成される. ほかに PROVISIONED というモードがあるが,これはかなり高度なケースを除いて使用しないだろう.

  • removal_policy: CloudFormation のスタックが消去されたときに, DynamoDB も一緒に消去されるかどうかを指定する. このコードでは DESTROY を選んでいるので,すべて消去される. ほかのオプションを選択すると,スタックを消去しても DynamoDB のバックアップを残す,などの動作を定義することができる.

デプロイ

デプロイの手順は,これまでのハンズオンとほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). シークレットキーの設定も忘れずに (AWS CLI のインストール).

sh
# プロジェクトのディレクトリに移動
$ cd handson/serverless/dynamodb

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd handson/serverless/dynamodb

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイのコマンドが無事に実行されれば, figure_title のような出力が得られるはずである. ここで表示されている SimpleDynamoDb.TableName = XXXX の XXXX の文字列は後で使うのでメモしておこう.

CDKデプロイ実行後の出力

AWS コンソールにログインして,デプロイされたスタックを確認してみよう. コンソールから, DynamoDB のページに行き,左のメニューバーから "Tables" を選択する. すると, figure_title のような画面からテーブルの一覧が確認できる.

DynamoDB のコンソール (テーブルの一覧)

今回のアプリケーションで作成したのが SimpleDynamoDb で始まるランダムな名前のついたテーブルだ. テーブルの名前をクリックして,詳細を見てみる. すると figure_title のような画面が表示されるはずだ. "Items" のタブをクリックすると,テーブルの中のレコードを確認できる. 現時点ではなにもデータを書き込んでいないので,空である.

DynamoDB のコンソール (テーブルの詳細画面)

データの読み書き

それでは, デプロイ で作ったテーブルを使ってデータの読み書きを実践してみよう. ここでは Python と boto3 ライブラリを用いた方法を紹介する.

まずは,テーブルに新しい要素を追加してみよう. ハンズオンのディレクトリにある simple_write.py を開いてみよう. 中には次のような関数が書かれている.

python
import boto3
from uuid import uuid4
ddb = boto3.resource('dynamodb')

def write_item(table_name):
    table = ddb.Table(table_name)
    table.put_item(
    Item={
        'item_id': str(uuid4()),
        'first_name': 'John',
        'last_name': 'Doe',
        'age': 25,
        }
    )
import boto3
from uuid import uuid4
ddb = boto3.resource('dynamodb')

def write_item(table_name):
    table = ddb.Table(table_name)
    table.put_item(
    Item={
        'item_id': str(uuid4()),
        'first_name': 'John',
        'last_name': 'Doe',
        'age': 25,
        }
    )

コードを上から読んでいくと,まず最初に boto3 ライブラリをインポートし, dynamodb のリソースを呼び出している. write_item() 関数は, DynamoDB のテーブルの名前 (上で見た SimpleDynamoDb-XXXX) を引数として受け取る. そして, put_item() メソッドを呼ぶことで,新しいアイテムを DB に書き込んでいる. アイテムには item_id, first_name, last_name, age の 4 つの属性が定義されている. ここで, item_id は先ほど説明した Partition key に相当しており, UUID4 を用いたランダムな文字列を割り当てている.

では, simple_write.py を実行してみよう. "XXXX" の部分を自分がデプロイしたテーブルの名前 (SimpleDynamoDb で始まる文字列) に置き換えたうえで,次のコマンドを実行する.

sh
$ python simple_write.py XXXX
$ python simple_write.py XXXX

新しい要素が正しく書き込めたか, AWS コンソールから確認してみよう. figure_title と同じ手順で,テーブルの中身の要素の一覧を表示する. すると figure_title のように,期待通り新しい要素が見つかるだろう.

DynamoDB に新しい要素が追加されたことを確認

boto3 を使ってテーブルから要素を読みだすことも可能である. ハンズオンのディレクトリにある simple_read.py を見てみよう.

python
import boto3
ddb = boto3.resource('dynamodb')

def scan_table(table_name):
    table = ddb.Table(table_name)
    items = table.scan().get("Items")
    print(items)
import boto3
ddb = boto3.resource('dynamodb')

def scan_table(table_name):
    table = ddb.Table(table_name)
    items = table.scan().get("Items")
    print(items)

table.scan().get("Items") によって,テーブルの中にあるすべての要素を読みだしている.

次のコマンドで,このスクリプトを実行してみよう ("XXXX" の部分を正しく置き換えることを忘れずに).

sh
$ python simple_read.py XXXX
$ python simple_read.py XXXX

先ほど書き込んだ要素が出力されることを確認しよう.

大量のデータの読み書き

DynamoDB の利点は,最初に述べたとおり,負荷に応じて自在にその処理能力を拡大できる点である.

そこで,ここでは一度に大量のデータを書き込む場合をシミュレートしてみよう. batch_rw.py に,一度に大量の書き込みを実行するためのプログラムが書いてある.

次のコマンドを実行してみよう (XXXX は自分のテーブルの名前に置き換える).

sh
$ python batch_rw.py XXXX write 1000
$ python batch_rw.py XXXX write 1000

このコマンドを実行することで,ランダムなデータが 1000 個データベースに書き込まれる.

さらに,データベースの検索をかけてみよう. 今回書き込んだデータには age という属性に 1 から 50 のランダムな整数が割り当てられている. age が 2 以下であるような要素だけを検索し拾ってくるには,次のコマンドを実行すればよい.

sh
$ python batch_rw.py XXXX search_under_age 2
$ python batch_rw.py XXXX search_under_age 2

上の 2 つのコマンドを何回か繰り返し実行してみて,データベースに負荷をかけてみよう. とくに大きな遅延なく結果が返ってくることが確認できるだろう.

スタックの削除

DynamoDB で十分に遊ぶことができたら,忘れずにスタックを削除しよう.

これまでのハンズオンと同様,スタックを削除するには,次のコマンドを実行すればよい.

sh
$ cdk destroy
$ cdk destroy

S3 ハンズオン

最後に, S3 の簡単なチュートリアルを紹介する. ハンズオンのソースコードは GitHub の handson/serverless/s3 に置いてある.

figure_title が今回提供する S3 チュートリアルの概要である. STEP 1 として, AWS CDK を用いて S3 に新しい空のバケット (Bucket) を作成する. 続いて STEP 2 では,データのアップロード・ダウンロードの方法を解説する.

S3 チュートリアルの概要

このハンズオンは,基本的に S3 の無料枠 の範囲内で実行することができる.

app.py にデプロイするプログラムが書かれている. 中身を見てみよう.

python
class SimpleS3(core.Stack):
    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        # S3 bucket to store data
        bucket = s3.Bucket(
            self, "bucket",
            removal_policy=core.RemovalPolicy.DESTROY,
            auto_delete_objects=True,
        )
class SimpleS3(core.Stack):
    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        # S3 bucket to store data
        bucket = s3.Bucket(
            self, "bucket",
            removal_policy=core.RemovalPolicy.DESTROY,
            auto_delete_objects=True,
        )

s3.Bucket() を呼ぶことによって空のバケットが新規に作成される. 上記のコードだと,バケットの名前は自動生成される. もし,自分の指定した名前を与えたい場合は, bucket_name というパラメータを指定すればよい. その際, バケットの名前はユニークでなければならない (i.e. AWS のデプロイが行われるリージョン内で名前の重複がない) 点に注意しよう. もし,同じ名前のバケットが既に存在する場合はエラーが返ってくる.

デフォルトでは, CloudFormation スタックが削除されたとき, S3 バケットとその中に保存されたファイルは削除されない. これは,大切なデータを誤って消してしまうことを防止するための安全策である. cdk destroy を実行したときにバケットも含めてすべて削除されるようにするには, removal_policy=core.RemovalPolicy.DESTROY, auto_delete_objects=True とパラメータを設定する. 結果もよく理解したうえで,自分の用途にあった適切なパラメータを設定しよう.

デプロイ

デプロイの手順は,これまでのハンズオンとほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). シークレットキーの設定も忘れずに (AWS CLI のインストール).

sh
# プロジェクトのディレクトリに移動
$ cd handson/serverless/s3

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd handson/serverless/s3

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイを実行すると, figure_title のような出力が得られるはずである. ここで表示されている SimpleS3.BucketName = XXXX が,新しく作られたバケットの名前である (今回提供しているコードを使うとランダムな名前がバケットに割り当てられる). これはあとで使うのでメモしておこう.

デプロイ実行後の出力

データの読み書き

スタックのデプロイが完了したら,早速バケットにデータをアップロードしてみよう.

まずは,以下のコマンドを実行して, tmp.txt という仮のファイルを生成する.

sh
$ echo "Hello world!" >> tmp.txt
$ echo "Hello world!" >> tmp.txt

ハンズオンのディレクトリにある simple_s3.pyboto3 ライブラリを使用した S3 のファイルのアップロード・ダウンロードのスクリプトが書いてある. simple_s3.py を使って,上で作成した tmp.txt を以下のコマンドによりバケットにアップロードする. XXXX のところは,自分自身のバケットの名前で置き換えること.

sh
$ python simple_s3.py XXXX upload tmp.txt
$ python simple_s3.py XXXX upload tmp.txt

simple_s3.py のアップロードを担当している部分を以下に抜粋する.

python
def upload_file(bucket_name, filename, key=None):
    bucket = s3.Bucket(bucket_name)

    if key is None:
        key = os.path.basename(filename)

    bucket.upload_file(filename, key)
def upload_file(bucket_name, filename, key=None):
    bucket = s3.Bucket(bucket_name)

    if key is None:
        key = os.path.basename(filename)

    bucket.upload_file(filename, key)

bucket = s3.Bucket(bucket_name) の行で Bucket() オブジェクトを呼び出している. そして, upload_file() メソッドを呼ぶことでファイルのアップロードを実行している.

S3 においてファイルの識別子として使われるのが Key である. これは,従来的なファイルシステムにおけるパス (Path) と相同な概念で,それぞれのファイルに固有な Key が割り当てられる必要がある. Key という呼び方は, S3 が Object storage と呼ばれるシステムに立脚していることに由来する. --key のオプションを追加して simple_s3.py を実行することで, Key を指定してアップロードを実行することができる.

sh
$ python simple_s3.py XXXX upload tmp.txt --key a/b/tmp.txt
$ python simple_s3.py XXXX upload tmp.txt --key a/b/tmp.txt

ここではアップロードされたファイルに a/b/tmp.txt という Key を割り当てている.

ここまでコマンドを実行し終えたところで,一度 AWS コンソールに行き S3 の中身を確認してみよう. S3 のコンソールに行くと,バケットの一覧が見つかるはずである. その中から, simples3-bucket から始まるランダムな名前のついたバケットを探し,クリックする. するとバケットの中に含まれるファイルの一覧が表示される (figure_title).

S3 バケットの中のファイル一覧

ここで実行した 2 つのコマンドによって, tmp.txt というファイルと, a/b/tmp.txt というファイルが見つかることに注目しよう. 従来的なファイルシステムと似た体験を提供するため, S3 では Key が "/" (スラッシュ) によって区切られていた場合,ツリー状の階層構造によってファイルを管理することができる.

オブジェクトストレージには本来ディレクトリという概念はない. 上で紹介した "/" による階層づけはあくまでユーザー体験向上の目的のお化粧的な機能である.

次に,バケットからファイルのダウンロードを実行してみよう. simple_s3.py を使って,以下のコマンドを実行すればよい. XXXX のところは,自分自身のバケットの名前で置き換えること.

sh
$ python simple_s3.py XXXX download tmp.txt
$ python simple_s3.py XXXX download tmp.txt

simple_s3.py のダウンロードを担当している部分を以下に抜粋する.

python
def download_file(bucket_name, key, filename=None):
    bucket = s3.Bucket(bucket_name)

    if filename is None:
        filename = os.path.basename(key)

    bucket.download_file(key, filename)
def download_file(bucket_name, key, filename=None):
    bucket = s3.Bucket(bucket_name)

    if filename is None:
        filename = os.path.basename(key)

    bucket.download_file(key, filename)

S3 からのダウンロードはシンプルで, download_file() メソッドを使って,ダウンロードしたい対象の Key を指定すればよい. ローカルのコンピュータでの保存先のパスを 2 個目の引数として渡している.

スタックの削除

以上のハンズオンで, S3 の一番基本的な使い方を紹介した. ここまでのハンズオンが理解できたら,忘れずにスタックを削除しよう. これまでのハンズオンと同様,スタックを削除するには,次のコマンドを実行すればよい.

sh
$ cdk destroy
$ cdk destroy

Hands-on #6: Bashoutter

さて,最後のハンズオンとなる第六回では,これまで学んできたサーバーレスクラウドの技術を使って,簡単なウェブサービスを作ってみよう. 具体的には,人々が自分の作った俳句を投稿する SNS サービス (Bashoutter と名付ける) を作成してみよう. Lambda, DynamoDB, S3 などの技術をすべて盛り込み,シンプルながらもサーバーレスの利点を生かしたスケーラブルな SNS アプリが誕生する. 最終的には, figure_title のような,ミニマルではあるがとても現代風な SNS サイトが完成する!

ハンズオン#6で作製する SNS アプリケーション "Bashoutter"

準備

ハンズオンのソースコードは GitHub の handson/bashoutter に置いてある.

本ハンズオンの実行には,第一回ハンズオンで説明した準備 (準備) が整っていることを前提とする. それ以外に必要な準備はない.

このハンズオンは,基本的に AWS の無料枠 の範囲内で実行できる.

アプリケーションの説明

API

今回のアプリケーションでは,人々からの俳句の投稿を受け付けたり,投稿された俳句の一覧を取得する,といった機能を実装したい. この機能を実現するための最小限の設計として, table_title に示すような四つの REST API を今回は実装する. 俳句を投稿する,閲覧する,削除するという基本的なデータ操作を行うための API が完備されている. また, PATCH /haiku/{item_id} は, {item_id} で指定された俳句に”いいね”をするために使用する.

Bashoutter API

GET /haiku

俳句の一覧を取得する

POST /haiku

新しい俳句を投稿する

PATCH /haiku/{item_id}

{item_id} で指定された俳句にお気に入り票を一つ入れる

DELETE /haiku/{item_id}

{item_id} で指定された俳句を削除する

それぞれの API のパラメータおよび返り値の詳細は,ハンズオンのソースコードの中の swagger.yml に定義してある.

Open API Specification (OAS; 少し前は Swagger Specification とよばれていた) は, REST API のための記述フォーマットである. OAS に従って API の仕様が記述されていると,簡単にドキュメンテーションを生成したり,クライアントアプリケーションを自動生成することができる. 今回用意した API 仕様 も, OAS に従って書いてある. 詳しくは Swagger の公式ドキュメンテーション などを参照.

アプリケーションアーキテクチャ

このハンズオンで作成するアプリケーションの概要を figure_title に示す.

ハンズオン#5で作製するアプリケーションのアーキテクチャ

簡単にまとめると,次のような設計である.

  • クライアントからの API リクエストは, API Gateway (後述)にまず送信され, API の URI で指定された Lambda 関数へ転送される.

  • それぞれの API のパス (リソース) ごとに独立した Lambda を用意する.

  • 俳句の情報 (作者,本文,投稿日時など) を記録するためのデータベース (DynamoDB) を用意する.

  • 各 Lambda 関数には, DynamoDB へのアクセス権を付与する.

  • 最後に,ウェブブラウザからコンテンツを表示できるよう, ウェブページの静的コンテンツを配信するための S3 バケットを用意する.クライアントはこの S3 バケットにアクセスすることで HTML/CSS/JS などのコンテンツを取得する.

それでは,プログラムのソースコードを見てみよう (handson/bashoutter/app.py).

python
class Bashoutter(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        # dynamoDB table to store haiku
        table = ddb.Table(
            self, "Bashoutter-Table",
            partition_key=ddb.Attribute(
                name="item_id",
                type=ddb.AttributeType.STRING
            ),
            billing_mode=ddb.BillingMode.PAY_PER_REQUEST,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        #
        bucket = s3.Bucket(
            self, "Bashoutter-Bucket",
            website_index_document="index.html",
            public_read_access=True,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        common_params = {
            "runtime": _lambda.Runtime.PYTHON_3_7,
            "environment": {
                "TABLE_NAME": table.table_name
            }
        }

        #
        # define Lambda functions
        get_haiku_lambda = _lambda.Function(
            self, "GetHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.get_haiku",
            memory_size=512,
            **common_params,
        )
        post_haiku_lambda = _lambda.Function(
            self, "PostHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.post_haiku",
            **common_params,
        )
        patch_haiku_lambda = _lambda.Function(
            self, "PatchHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.patch_haiku",
            **common_params,
        )
        delete_haiku_lambda = _lambda.Function(
            self, "DeleteHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.delete_haiku",
            **common_params,
        )

        #
        # grant permissions
        table.grant_read_data(get_haiku_lambda)
        table.grant_read_write_data(post_haiku_lambda)
        table.grant_read_write_data(patch_haiku_lambda)
        table.grant_read_write_data(delete_haiku_lambda)

        #
        # define API Gateway
        api = apigw.RestApi(
            self, "BashoutterApi",
            default_cors_preflight_options=apigw.CorsOptions(
                allow_origins=apigw.Cors.ALL_ORIGINS,
                allow_methods=apigw.Cors.ALL_METHODS,
            )
        )

        haiku = api.root.add_resource("haiku")
        haiku.add_method(
            "GET",
            apigw.LambdaIntegration(get_haiku_lambda)
        )
        haiku.add_method(
            "POST",
            apigw.LambdaIntegration(post_haiku_lambda)
        )

        haiku_item_id = haiku.add_resource("{item_id}")
        haiku_item_id.add_method(
            "PATCH",
            apigw.LambdaIntegration(patch_haiku_lambda)
        )
        haiku_item_id.add_method(
            "DELETE",
            apigw.LambdaIntegration(delete_haiku_lambda)
        )
class Bashoutter(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        # dynamoDB table to store haiku
        table = ddb.Table(
            self, "Bashoutter-Table",
            partition_key=ddb.Attribute(
                name="item_id",
                type=ddb.AttributeType.STRING
            ),
            billing_mode=ddb.BillingMode.PAY_PER_REQUEST,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        #
        bucket = s3.Bucket(
            self, "Bashoutter-Bucket",
            website_index_document="index.html",
            public_read_access=True,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        common_params = {
            "runtime": _lambda.Runtime.PYTHON_3_7,
            "environment": {
                "TABLE_NAME": table.table_name
            }
        }

        #
        # define Lambda functions
        get_haiku_lambda = _lambda.Function(
            self, "GetHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.get_haiku",
            memory_size=512,
            **common_params,
        )
        post_haiku_lambda = _lambda.Function(
            self, "PostHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.post_haiku",
            **common_params,
        )
        patch_haiku_lambda = _lambda.Function(
            self, "PatchHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.patch_haiku",
            **common_params,
        )
        delete_haiku_lambda = _lambda.Function(
            self, "DeleteHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.delete_haiku",
            **common_params,
        )

        #
        # grant permissions
        table.grant_read_data(get_haiku_lambda)
        table.grant_read_write_data(post_haiku_lambda)
        table.grant_read_write_data(patch_haiku_lambda)
        table.grant_read_write_data(delete_haiku_lambda)

        #
        # define API Gateway
        api = apigw.RestApi(
            self, "BashoutterApi",
            default_cors_preflight_options=apigw.CorsOptions(
                allow_origins=apigw.Cors.ALL_ORIGINS,
                allow_methods=apigw.Cors.ALL_METHODS,
            )
        )

        haiku = api.root.add_resource("haiku")
        haiku.add_method(
            "GET",
            apigw.LambdaIntegration(get_haiku_lambda)
        )
        haiku.add_method(
            "POST",
            apigw.LambdaIntegration(post_haiku_lambda)
        )

        haiku_item_id = haiku.add_resource("{item_id}")
        haiku_item_id.add_method(
            "PATCH",
            apigw.LambdaIntegration(patch_haiku_lambda)
        )
        haiku_item_id.add_method(
            "DELETE",
            apigw.LambdaIntegration(delete_haiku_lambda)
        )
  • ここで,俳句の情報を記録しておくための DynamoDB テーブルを定義している.

  • 静的コンテンツを配信するための S3 バケットを用意している.

  • それぞれの API で実行される Lambda 関数を定義している. 関数は Python3.7 で書かれており,コードは handson/bashoutter/api/api.py にある.

  • <3> で定義された Lambda 関数に対し,データベースへの読み書きのアクセス権限を付与している.

  • ここで,API Gateway により,各 API パスとそこで実行されるべき Lambda 関数を紐付けている.

それぞれの項目について,もう少し詳しく説明しよう.

Public access mode の S3 バケット

S3 のバケットを作成しているコードを見てみよう.

python
bucket = s3.Bucket(
    self, "Bashoutter-Bucket",
    website_index_document="index.html",
    public_read_access=True,
    removal_policy=core.RemovalPolicy.DESTROY
)
bucket = s3.Bucket(
    self, "Bashoutter-Bucket",
    website_index_document="index.html",
    public_read_access=True,
    removal_policy=core.RemovalPolicy.DESTROY
)

ここで注目してほしいのは public_read_access=True の部分だ. 前章で, S3 について説明を行ったときには触れなかったが, S3 には Public access mode という機能がある. Public access mode をオンにしておくと,バケットの中のファイルは認証なしで (i.e. インターネット上の誰でも) 閲覧できるようになる. この設定は,一般公開されているウェブサイトの静的なコンテンツを置いておくのに最適であり,多くのサーバーレスによるウェブサービスでこのような設計が行われる. public access mode を設定しておくと, http://XXXX.s3-website-ap-northeast-1.amazonaws.com/ のような固有の URL がバケットに対して付与される. そして,クライアントがこの URL にアクセスをすると,バケットの中にある index.html がクライアントに返され,ページがロードされる (どのファイルが返されるかは, website_index_document="index.html" の部分で設定している.)

なお,この時点ではバケットは空である. HTML/CSS/JS など静的コンテンツの配置は,デプロイを行った後ほどのステップで行う.

より本格的なウェブページを運用する際には, public access mode の S3 バケットに, CloudFront という機能を追加することが一般的である. CloudFront により, Content Delivery Nework (CDN) や暗号化された HTTPS 通信を設定することができる. CloudFront についての詳細は 公式ドキュメンテーション "What is Amazon CloudFront?" などを参照いただきたい.

今回のハンズオンでは説明の簡略化のため CloudFront の設定を行わなかったが,興味のある読者は次のリンクのプログラムが参考になるだろう.

今回の S3 バケットには, AWS によって付与されたランダムな URL がついている. これを. example.com のような自分のドメインでホストしたければ, AWS によって付与された URL を自分のドメインの DNS レコードに追加すればよい.

API のハンドラ関数

API リクエストが来たときに,リクエストされた処理を行う関数のことをハンドラ (handler) 関数とよぶ. GET /haiku の API に対してのハンドラ関数を Lambda で定義している部分を見てみよう.

python
get_haiku_lambda = _lambda.Function(
    self, "GetHaiku",
    code=_lambda.Code.from_asset("api"),
    handler="api.get_haiku",
    memory_size=512,
    **common_params
)
get_haiku_lambda = _lambda.Function(
    self, "GetHaiku",
    code=_lambda.Code.from_asset("api"),
    handler="api.get_haiku",
    memory_size=512,
    **common_params
)

簡単なところから見ていくと, memory_size=512 の箇所でメモリーの使用量を 512MB に指定している. また, code=_lambda.Code.from_asset("api") によって外部のディレクトリ (api/) を参照せよと指定しており, handler="api.get_haiku" のところで api.py というファイルの get_haiku() という関数をハンドラ関数として実行せよ,と定義している.

次に,ハンドラ関数として使用されている get_haiku() のコードを見てみよう (handson/bashoutter/api/api.py).

python
ddb = boto3.resource("dynamodb")
table = ddb.Table(os.environ["TABLE_NAME"])

def get_haiku(event, context):
    """
    handler for GET /haiku
    """
    try:
        response = table.scan()

        status_code = 200
        resp = response.get("Items")
    except Exception as e:
        status_code = 500
        resp = {"description": f"Internal server error. {str(e)}"}
    return {
        "statusCode": status_code,
        "headers": HEADERS,
        "body": json.dumps(resp, cls=DecimalEncoder)
    }
ddb = boto3.resource("dynamodb")
table = ddb.Table(os.environ["TABLE_NAME"])

def get_haiku(event, context):
    """
    handler for GET /haiku
    """
    try:
        response = table.scan()

        status_code = 200
        resp = response.get("Items")
    except Exception as e:
        status_code = 500
        resp = {"description": f"Internal server error. {str(e)}"}
    return {
        "statusCode": status_code,
        "headers": HEADERS,
        "body": json.dumps(resp, cls=DecimalEncoder)
    }

response = table.scan() で,俳句の格納された DynamoDB テーブルから,すべての要素を取り出している. もしなにもエラーが起きなければステータスコード 200 が返され,もしなにかエラーが起こればステータスコード 500 が返されるようになっている.

上記のような操作を,ほかの API についても繰り返すことで,すべての API のハンドラ関数が定義されている.

GET /haiku のハンドラ関数で, response = table.scan() という部分があるが,実はこれは最善の書き方ではない. DynamoDB の scan() メソッドは,最大で 1MB までのデータしか返さない. データベースのサイズが大きく, 1MB 以上のデータがある場合には,再帰的に scan() メソッドをよぶ必要がある. 詳しくは boto3 ドキュメンテーション を参照.

AWS における権限の管理 (IAM)

以下の部分のコードに注目してほしい.

python
table.grant_read_data(get_haiku_lambda)
table.grant_read_write_data(post_haiku_lambda)
table.grant_read_write_data(patch_haiku_lambda)
table.grant_read_write_data(delete_haiku_lambda)
table.grant_read_data(get_haiku_lambda)
table.grant_read_write_data(post_haiku_lambda)
table.grant_read_write_data(patch_haiku_lambda)
table.grant_read_write_data(delete_haiku_lambda)

これまでは説明の簡略化のためにあえて触れてこなかったが, AWS には IAM (Identity and Access Management) という重要な概念がある. IAM は基本的に,あるリソースがほかのリソースに対してどのような権限をもっているか,を規定するものである. Lambda は,デフォルトの状態ではほかのリソースにアクセスする権限をなにも有していない. したがって, Lambda 関数が DynamoDB のデータを読み書きするためには,それを許可するような IAM が Lambda 関数に付与されていなければならない.

CDK による dynamodb.Table オブジェクトには grant_read_write_data() という便利なメソッドが備わっており,アクセスを許可したい Lambda 関数を引数としてこのメソッドを呼ぶことで,データベースへの読み書きを許可する IAM を付与することができる. 同様に,CDK の s3.Bucket オブジェクトにも grant_read_write() というメソッドが備わっており,これによってバケットへの読み書きを許可することができる. このメソッドは,実は Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する で AWS Batch によるクラスターを構成した際に使用した. 興味のある読者は振り返ってコードを確認してみよう.

各リソースに付与する IAM は,必要最低限の権限を与えるにとどめるというのが基本方針である. これにより,セキュリティを向上させるだけでなく,意図していないプログラムからのデータベースへの読み書きを防止するという点で,バグを未然に防ぐことができる.

そのような理由により,このコードでは GET のハンドラー関数に対しては grant_read_data() によって, read 権限のみを付与している.

API Gateway

API Gateway とは, API の"入り口"として,API のリクエストパスに従って Lambda や EC2 などに接続を行うという機能を担う (figure_title). Lambda や EC2 によって行われた処理の結果は,再び API Gateway を経由してクライアントに返される. このように,クライアントとバックエンドサーバーの間に立ち, API のリソースパスに応じて接続先を振り分けるようなサーバーをルーター,あるいはリバースプロキシとよんだりする. 従来的には,ルーターにはそれ専用の仮想サーバーが置かれることが一般的であった. しかし, API Gateway はサーバーレスなルーターとして,固定されたサーバーを配置することなく, API のリクエストが来たときのみ起動し,API のルーティングを実行する. サーバーレスであることの当然の帰結として,アクセスの件数が増大したときにはそれにルーティングの処理能力を自動で増やす機能も備わっている.

API Gateway

API Gateway を配置することで,大量 (1 秒間に数千から数万件) の API リクエストに対応することのできるシステムを容易に構築することができる. API Gateway の料金は table_title のように設定されている. また,無料利用枠により,月ごとに 100 万件までのリクエストは 0 円で利用できる.

API Gateway の利用料金設定 (参照)
Number of Requests (per month)Price (per million)

First 333 million

$4.25

Next 667 million

$3.53

Next 19 billion

$3.00

Over 20 billion

$1.91

ソースコードの該当箇所を見てみよう.

python
#
api = apigw.RestApi(
    self, "BashoutterApi",
    default_cors_preflight_options=apigw.CorsOptions(
        allow_origins=apigw.Cors.ALL_ORIGINS,
        allow_methods=apigw.Cors.ALL_METHODS,
    )
)

#
haiku = api.root.add_resource("haiku")
#
haiku.add_method(
    "GET",
    apigw.LambdaIntegration(get_haiku_lambda)
)
haiku.add_method(
    "POST",
    apigw.LambdaIntegration(post_haiku_lambda)
)

#
haiku_item_id = haiku.add_resource("{item_id}")
#
haiku_item_id.add_method(
    "PATCH",
    apigw.LambdaIntegration(patch_haiku_lambda)
)
haiku_item_id.add_method(
    "DELETE",
    apigw.LambdaIntegration(delete_haiku_lambda)
)
#
api = apigw.RestApi(
    self, "BashoutterApi",
    default_cors_preflight_options=apigw.CorsOptions(
        allow_origins=apigw.Cors.ALL_ORIGINS,
        allow_methods=apigw.Cors.ALL_METHODS,
    )
)

#
haiku = api.root.add_resource("haiku")
#
haiku.add_method(
    "GET",
    apigw.LambdaIntegration(get_haiku_lambda)
)
haiku.add_method(
    "POST",
    apigw.LambdaIntegration(post_haiku_lambda)
)

#
haiku_item_id = haiku.add_resource("{item_id}")
#
haiku_item_id.add_method(
    "PATCH",
    apigw.LambdaIntegration(patch_haiku_lambda)
)
haiku_item_id.add_method(
    "DELETE",
    apigw.LambdaIntegration(delete_haiku_lambda)
)
  • 最初に, api = apigw.RestApi() により,空の API Gateway を作成している.

  • 次に, api.root.add_resource() のメソッドを呼ぶことで, /haiku という API パスを追加している.

  • 続いて, add_method() を呼ぶことで, GET, POST のメソッドを /haiku のパスに定義している.

  • さらに, haiku.add_resource("{item_id}") により, /haiku/{item_id} という API パスを追加している.

  • 最後に, add_method() を呼ぶことにより, PATCH, DELETE のメソッドを /haiku/{item_id} のパスに定義している.

このように, API Gateway の使い方は非常にシンプルで,逐次的に API パスとそこで実行されるメソッド・Lambda を記述していくだけでよい.

このプログラムで 新規 API を作成すると, ランダムな URL がその API のエンドポイントとして割り当てられる. これを. api.example.com のような自分のドメインでホストしたければ, AWS によって付与された URL を自分のドメインの DNS レコードに追加すればよい.

API Gateway で新規 API を作成したとき, default_cors_preflight_options= というパラメータで Cross Origin Resource Sharing (CORS) の設定を行っている. これは,ブラウザで走る Web アプリケーションと API を接続するときに必要な設定である.

アプリケーションのデプロイ

アプリケーションの中身が理解できたところで,早速デプロイを行ってみよう. デプロイの手順は,これまでのハンズオンとほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). シークレットキーの設定も忘れずに (AWS CLI のインストール).

sh
# プロジェクトのディレクトリに移動
$ cd intro-aws/handson/bashoutter

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd intro-aws/handson/bashoutter

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイのコマンドが無事に実行されれば, figure_title のような出力が得られるはずである. ここで表示されている Bashoutter.BashoutterApiEndpoint = XXXX, Bashoutter.BucketUrl = YYYY の二つ文字列はあとで使うのでメモしておこう.

CDKデプロイ実行後の出力

AWS コンソールにログインして,デプロイされたスタックを確認してみよう. まずは,コンソールから API Gateway のページに行く. すると, figure_title のような画面が表示され,デプロイ済みの API エンドポイントの一覧が確認できる.

API Gateway コンソール画面 (1)

今回デプロイした "BashoutterApi" という名前の API をクリックすることで figure_title のような画面に遷移し,詳細情報を閲覧できる. GET /haiku, POST /haiku などが定義されていることが確認できる.

それぞれのメソッドをクリックすると,そのメソッドの詳細情報を確認できる. API Gateway は,前述したルーティングの機能だけでなく,認証機能などを追加することも可能である. このハンズオンではとくにこれらの機能は使用しないが, "Method Request" と書いてある項目などがそれに相当する. 次に, figure_title で画面右端の赤色で囲った部分に,この API で呼ばれる Lambda 関数が指定されていることに注目しよう. 関数名をクリックと,該当する Lambda のコンソールに遷移し,関数の中身を閲覧することが可能である.

API Gateway コンソール画面 (2)

次に, S3 のコンソール画面に移ってみよう. bashouter- で始まるランダムな名前のバケットが見つかるはずである (figure_title).

S3 コンソール画面

バケットの名前をクリックすることで,バケットの中身を確認してみよう. index.html のほか, css/, js/ などのディレクトリがあるのが確認できるだろう (figure_title). これらが,ウェブページの"枠"を定義している静的コンテンツである.

S3 バケットの中身

API リクエストを送信する

それでは,デプロイしたアプリケーションに対し,実際に API リクエストを送信してみよう. まずはコマンドラインから API を送信する演習を行おう. S3 に配置した GUI は一旦おいておく.

ここではコマンドラインから HTTP API リクエストを送信するためのシンプルな HTTP クライアントである HTTPie を使ってみよう. HTTPie は,スタックをデプロイするときに Python 仮想環境 (venv) を作成したとき,一緒にインストールされている. 念のためインストールがうまくいっているか確認するには,仮想環境を立ち上げたあとコマンドラインに http と打ってみる. ヘルプのメッセージが出力されたら準備 OK である.

まず,先ほどデプロイを実行したときに得られた API のエンドポイントの URL (Bashoutter.BashoutterApiEndpoint = XXXX で得られた XXXX の文字列) をコマンドラインの変数に設定しておく.

sh
$ export ENDPOINT_URL=XXXX
$ export ENDPOINT_URL=XXXX

次に,俳句の一覧を取得するため, GET /haiku の API を送信してみよう.

sh
$ http GET "${ENDPOINT_URL}/haiku"
$ http GET "${ENDPOINT_URL}/haiku"

現時点では,まだだれも俳句を投稿していないので,空の配列 ([]) が返ってくる.

それでは次に, POST /haiku を使って俳句を投稿してみよう.

sh
$ http POST "${ENDPOINT_URL}/haiku" \
username="松尾芭蕉" \
first="閑さや" \
second="岩にしみ入る" \
third="蝉の声"
$ http POST "${ENDPOINT_URL}/haiku" \
username="松尾芭蕉" \
first="閑さや" \
second="岩にしみ入る" \
third="蝉の声"

次のような出力が得られるだろう.

sh
HTTP/1.1 201 Created
Connection: keep-alive
Content-Length: 49
Content-Type: application/json
....
{
    "description": "Successfully added a new haiku"
}
HTTP/1.1 201 Created
Connection: keep-alive
Content-Length: 49
Content-Type: application/json
....
{
    "description": "Successfully added a new haiku"
}

新しい俳句を投稿することに成功したようである. 本当に俳句が追加されたか,再び GET リクエストを呼ぶことで確認してみよう.

sh
$ http GET "${ENDPOINT_URL}/haiku"

HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 258
Content-Type: application/json
...
[
    {
        "created_at": "2020-07-06T02:46:04+00:00",
        "first": "閑さや",
        "item_id": "7e91c5e4d7ad47909e0ac14c8bbab05b",
        "likes": 0.0,
        "second": "岩にしみ入る",
        "third": "蝉の声",
        "username": "松尾芭蕉"
    }
]
$ http GET "${ENDPOINT_URL}/haiku"

HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 258
Content-Type: application/json
...
[
    {
        "created_at": "2020-07-06T02:46:04+00:00",
        "first": "閑さや",
        "item_id": "7e91c5e4d7ad47909e0ac14c8bbab05b",
        "likes": 0.0,
        "second": "岩にしみ入る",
        "third": "蝉の声",
        "username": "松尾芭蕉"
    }
]

素晴らしい!

次に, PATCH /haiku/{item_id} を呼ぶことでこの俳句にいいねを追加してみよう. 一つ前のコマンドで取得した俳句の item_id を,次のコマンドの XXXX に代入した上で実行しよう.

sh
$ http PATCH "${ENDPOINT_URL}/haiku/XXXX"
$ http PATCH "${ENDPOINT_URL}/haiku/XXXX"

{"description": "OK"} という出力が得られるはずである. 再び GET リクエストを送ることで,いいね (likes) が 1 増えたことを確認しよう.

sh
$ http GET "${ENDPOINT_URL}/haiku"
...
[
    {
        ...
        "likes": 1.0,
        ...
    }
]
$ http GET "${ENDPOINT_URL}/haiku"
...
[
    {
        ...
        "likes": 1.0,
        ...
    }
]

最後に, DELETE リクエストを送ることで俳句をデータベースから削除しよう. XXXXitem_id の値で置き換えたうえで次のコマンドを実行する.

sh
$ http DELETE "${ENDPOINT_URL}/haiku/XXXX"
$ http DELETE "${ENDPOINT_URL}/haiku/XXXX"

再び GET リクエストを送ることで,返り値が空 ([]) になっていることを確認しよう.

これで,俳句の投稿・取得・削除そしていいねの追加,といった基本的な API がきちんと動作していることが確認できた.

大量の API リクエストをシミュレートする

さて,前節ではマニュアルで一つずつ俳句を投稿した. 多数のユーザーがいるような SNS では,1 秒間に数千件以上の投稿がされている. 今回はサーバーレスアーキテクチャを採用したことで,そのような瞬間的な大量アクセスにも容易に対応できるようなシステムが自動的に構築されている. このポイントを実証するため,ここでは大量の API が送信された状況をシミュレートしてみよう.

handson/bashoutter/client.py に,大量の API リクエストをシミュレートするためのプログラムが書かれている. このプログラムを使用すると, POST /haiku の API リクエストを指定された回数だけ実行することができる.

テストとして, API を 300 回実行してみよう. 次のコマンドを実行する.

sh
$ python client.py $ENDPOINT_URL post_many 300
$ python client.py $ENDPOINT_URL post_many 300

数秒のうちに実行が完了するだろう. これがもし,単一のサーバーからなる API だったとしたら,このような大量のリクエストの処理にはもっと時間がかかっただろう. 最悪の場合には,サーバーダウンにもつながっていたかもしれない. したがって,今回作成したサーバーレスアプリケーションは,とてもシンプルながらも 1 秒間に数百件の処理を行えるような,スケーラブルなクラウドシステムであることがわかる. サーバーレスでクラウドを設計することの利点を垣間見ることができただろうか?

先述のコマンドにより大量の俳句を投稿するとデータベースに無駄なデータがどんどん溜まってしまう. データベースを完全に空にするには,次のコマンドを使用する.

sh
$ python client.py $ENDPOINT_URL clear_database
$ python client.py $ENDPOINT_URL clear_database

Bashoutter GUI を動かしてみる

前節ではコマンドラインから API を送信する演習を行った. ウェブアプリケーションでは,これと同じことがウェブブラウザの背後で行われ,ページのコンテンツが表示されている (figure_title 参照). 最後に, API が GUI と統合されるとどうなるのか,見てみよう.

CDK のコードで, Public access mode の S3 バケットを作成したことを思い出してほしい. 最初のステップとして,ここにウェブサイトのコンテンツをアップロードしよう. ハンズオンのソースコードの中に gui/dist というフォルダが見つかるはずである. ここにはビルド済みのウェブサイトの静的コンテンツ (HTML/CSS/JavaScript) が入っている. AWS CLI のコマンドを使うことでこれらのファイルを S3 にアップロードしよう.

sh
$ aws s3 cp --recursive ./gui/dist s3://<BUCKET_NAME>
$ aws s3 cp --recursive ./gui/dist s3://<BUCKET_NAME>

コマンドを実行する際は, Bashoutter ハンズオンのディレクトリから行うこと (./gui/dist に注目),そして <BUCKET_NAME> にはデプロイした自身のバケットの名前が入る点に注意. 念のため,AWS コンソールにログインし,バケットにファイルがアップロードされている点を確認しておこう.

なお,今回は GUI の説明はとくに行わないが, Bashoutter のウェブサイトは Vue.jsVuetify という UI フレームワークを使って作成した. Vue を使うことで, Single page application (SPA) の技術でウェブサイトの画面がレンダリングされる. ソースコードは handson/bashoutter/gui のディレクトリの中にあるので,興味のある読者は確認してみるとよい.

アップトードが完了したところで,続いてデプロイを実行したときにコマンドラインの出力を見直してみよう. Bashoutter.BucketUrl= で与えられた URL が見つかるはずである (figure_title). これは,先述したとおり, Public access mode の S3 バケットの URL である.

ウェブブラウザを開き,アドレスバーに S3 の URL を入力しへアクセスしてみよう. すると, figure_title のようなページが表示されるはずである.

"Bashoutter" の GUI 画面

ページが表示されたら,一番上の "API Endpoint URL" と書いてあるテキストボックスに,今回デプロイした API Gateway の URL を入力する (今回のアプリケーションでは,API Gateway の URL はランダムに割り当てられるのでこのような GUI の仕様になっている). そうしたら,画面の "REFRESH" と書いてあるボタンを押してみよう. データベースに俳句が登録済みであれば,俳句の一覧が表示されるはずである. 各俳句の左下にあるハートのアイコンをクリックすることで, "like" の票を入れることができる.

新しい俳句を投稿するには,五七五と投稿者の名前を入力して, "POST" を押す. "POST" を押した後は,再び "REFRESH" ボタンを押すことで最新の俳句のリストをデータベースから取得する.

アプリケーションの削除

これで, Bashoutter プロジェクトが完成した! この SNS は,インターネットを通じて世界のどこからでもアクセスできる状態にある. また, 大量の API リクエストをシミュレートする で見たように,大量のユーザーの同時アクセスによる負荷がかかっても,柔軟にスケールが行われ遅延なく処理を行うことができる. 極めて簡素ながらも,立派なウェブサービスとしてのスペックは満たしているのである!

Bashoutter アプリを存分に楽しむことができたら,最後に忘れずにスタックを削除しよう.

コマンドラインからスタックの削除を実行するには,次のコマンドを使う.

sh
$ cdk destroy
$ cdk destroy

CDK のバージョンによっては S3 のバケットが空でないと, cdk destroy がエラーを出力する場合がある. この場合はスタックを削除する前に, S3 バケットの中身をすべて削除しなければならない.

コンソールから実行するには, S3 コンソールに行き,バケットの中身を開いたうえで,すべてのファイルを選択し, "Actions" → "Delete" を実行すればよいい.

コマンドラインから実行するには, 次のコマンドを使う. <BUCKET NAME> のところは,自分の バケットの名前 ("BashoutterBucketXXXX" というパターンの名前がついているはずである) に置き換えることを忘れずに.

sh
$ aws s3 rm <BUCKET NAME> --recursive
$ aws s3 rm <BUCKET NAME> --recursive

小括

ここまでが,本書第三部の内容であった.

第三部では,クラウドの応用として,一般の人に使ってもらうようなウェブアプリケーション・データベースをどのようにして作るのか,という点に焦点を当てて,説明を行った. その中で,従来的なクラウドシステムの設計と,ここ数年の最新の設計方法であるサーバーレスアーキテクチャについて解説した. Hands-on #5: サーバーレス入門 では, AWS でのサーバーレスの実践として, Lambda, S3, DynamoDB のハンズオンを行った. 最後に, Hands-on #6: Bashoutter では,これらの技術を統合することで,完全サーバーレスなウェブアプリケーション "Bashoutter" を作成した.

これらの演習を通じて,世の中のウェブサービスがどのようにしてでき上がっているのか,少し理解が深まっただろうか? また,そのようなウェブアプリケーションを自分が作りたいと思ったとき,今回のハンズオンがその出発点となることができたならば幸いである.

まとめ

Appendix: 環境構築

本書を読み進めるにあたって,ハンズオンのプログラムを実行するための環境を自分のローカルマシンにセットアップしなければならない. ここでは, AWS やコマンドラインの初心者を想定して,本章で必要なソフトウェアやライブラリのインストールなどを簡単に解説する. 以下に簡単な目次を示そう. 既に環境構築が済んでいる場合は適宜読み飛ばしていただき,関係のある箇所のみ目を通せば良い.

使用する OS は Linux/Mac/Windows のどれを用いても構わない. Windows のユーザーは, Windows Subsytem for Linux (WSL) を使用することを想定している (WSL のインストール).

また,本書のハンズオンを実行するための Docker イメージ を提供している. これを用いると, AWS CLI/CDK や Python の設定などをスキップできるので, Docker の使用方法を知っている読者には便利だろう.

AWS アカウントの取得

本書で提供するハンズオンを実際に自分で試すには,読者自身で AWS のアカウントの作成をする必要がある. 詳しいアカウントの作成の手順は 公式のドキュメンテーション に書かれているので,そちらも参照していただきたい. 以下の手順に従ってアカウントの作成を行う.

まず,ウェブブラウザから AWS コンソール にアクセスし,右上の Create an AWS Account をクリックする (figure_title で実線で囲った部分).

サインアップ (1): AWS コンソールにアクセス

次に,遷移した先のページでメールアドレスとパスワードなどの登録を行う (figure_title).

サインアップ (2): メールアドレス・パスワードなどの登録.

続いて,住所や電話番号などを訊かれるので,すべて入力しよう (figure_title).

サインアップ (3): 住所・電話番号の入力

次に,クレジットカードの情報の登録を求められる (figure_title). 個人で AWS を利用する場合は,利用料金の請求はクレジットカードを経由して行われる. クレジットカードの登録なしには AWS を使い始めることはできないことに注意.

サインアップ (4): クレジットカードの登録

次の画面では,携帯電話の SMS またはボイスメッセージを利用した本人確認が求められる (figure_title). 希望の認証方法を選択し,自分の携帯電話番号を入力しよう.

サインアップ (5): 携帯電話による本人確認

無事に本人確認が完了すると,最後にサポートプランの選択を求められる (figure_title). 無料の Basic support を選択しておけば問題ない.

サインアップ (6): サポートプランの選択

以上のステップにより,アカウントの作成が完了する (figure_title). 早速ログインをして, AWS コンソールにアクセスできるか確認しておこう.

サインアップ (7): アカウントの作成が完了した

AWS のシークレットキーの作成

AWS シークレットキーとは, AWS CLI や AWS CDK から AWS の API を操作するときに,ユーザー認証を行うための鍵のことである. AWS CLI/CDK を使うには,最初にシークレットキーを発行する必要がある. AWS シークレットキーの詳細は 公式ドキュメンテーション "Understanding and getting your AWS credentials" を参照.

  1. AWS コンソールにログインする.

  2. 画面右上のアカウント名をクリックし,表示されるプルダウンメニューから "My Security Credentials" を選択 (figure_title)

  3. "Access keys for CLI, SDK, & API access" の下にある "Create accesss key" のボタンをクリックする (figure_title)

  4. 表示された Access key ID, Secret access key を記録しておく (画面を閉じると二度と表示されない).

  5. 鍵を忘れてしまった場合などは,同じ手順で再発行が可能である.

  6. 発行したシークレットキーは, ~/.aws/credentials のファイルに書き込むか,環境変数に設定するなどして使う (詳しくは AWS CLI のインストール).

AWS シークレットキーの発行1

AWS シークレットキーの発行2

AWS Educate Starter Account を用いている場合は,次の手順でシークレットキーを確認する.

  • AWS Educate のコンソール画面から, vocareum のコンソールに移動する (figure_title).

  • Account Details をクリックし,続いて AWS CLI: Show をクリックする.

  • aws_access_key_id, aws_secret_access_key, aws_session_token が表示される (figure_title). ここで表示された内容を ~/.aws/credentials にコピーする (AWS CLI のインストール 参照). aws_session_token の箇所も漏らさずコピーすること.

  • 続いて, ~/.aws/config というファイルを用意し,次の内容を書き込む. 現時点では AWS Starter Account は us-east-1 リージョンでしか利用できないためである.

    [default] region = us-east-1 output = json

  • 上記の説明ではプロファイル名が default となっていたが,これは自分の好きな名前に変更してもよい. default 以外の名前を使用する場合は,コマンドを実行するときにプロファイル名を指定する必要がある (詳しくは AWS CLI のインストール).

vocareum コンソール

vocareum から AWS シークレットキーの発行

AWS CLI のインストール

読者のために,執筆時点におけるインストールの手順 (Linux 向け) を簡単に記述する. 将来のバージョンでは変更される可能性があるので,常に 公式のドキュメンテーション で最新の情報をチェックすることを忘れずに.

sh
$ curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
$ unzip awscliv2.zip
$ sudo ./aws/install
$ curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
$ unzip awscliv2.zip
$ sudo ./aws/install

インストールできたか確認するため,次のコマンドを打ってバージョン情報が出力されることを確認する.

sh
$ aws --version
$ aws --version

インストールができたら,次のコマンドにより初期設定を行う (参照).

sh
$ aws configure
$ aws configure

コマンドを実行すると, AWS Access Key ID, AWS Secret Access Key を入力するよう指示される. シークレットキーの発行については AWS のシークレットキーの作成 を参照. コマンドは加えて,Default region name を訊いてくる. ここには自分の好きな地域 (例えば ap-northeast-1 =東京リージョン) を指定すればよい. 最後の Default output formatjson としておくとよい.

このコマンドを完了すると, ~/.aws/credentials~/.aws/config という名前のファイルが生成されているはずである. 念のため, cat コマンドを使って中身を確認してみるとよい.

sh
$ cat ~/.aws/credentials
[default]
aws_access_key_id = XXXXXXXXXXXXXXXXXX
aws_secret_access_key = YYYYYYYYYYYYYYYYYYY

$ cat ~/.aws/config
[profile default]
region = ap-northeast-1
output = json
$ cat ~/.aws/credentials
[default]
aws_access_key_id = XXXXXXXXXXXXXXXXXX
aws_secret_access_key = YYYYYYYYYYYYYYYYYYY

$ cat ~/.aws/config
[profile default]
region = ap-northeast-1
output = json

~/.aws/credentials には認証鍵の情報が, ~/.aws/config には AWS CLI の設定が記録されている.

デフォルトでは, [default] という名前でプロファイルが保存される. いくつかのプロファイルを使い分けたければ, default の例に従って,たとえば [myprofile] などという名前でプロファイルを追加すればよい.

AWS CLI でコマンドを打つときに,プロファイルを使い分けるには,

sh
$ aws s3 ls --profile myprofile
$ aws s3 ls --profile myprofile

のように, --profile というオプションをつけてコマンドを実行する.

いちいち --profile オプションをつけるのが面倒だと感じる場合は, AWS_PROFILE という環境変数を設定するとよい.

sh
$ export AWS_PROFILE=myprofile
$ export AWS_PROFILE=myprofile

あるいは,認証情報などを環境変数に設定するテクニックもある.

sh
export AWS_ACCESS_KEY_ID=XXXXXX
export AWS_SECRET_ACCESS_KEY=YYYYYY
export AWS_DEFAULT_REGION=ap-northeast-1
export AWS_ACCESS_KEY_ID=XXXXXX
export AWS_SECRET_ACCESS_KEY=YYYYYY
export AWS_DEFAULT_REGION=ap-northeast-1

これらの環境変数は, ~/.aws/credentials よりも高い優先度をもつので,環境変数が設定されていればそちらの情報が使用される (参照).

AWS Educate Starter Accountus-east-1 のリージョンのみ利用可能である (執筆時点での情報). よって, AWS Educate Starter Account を使用している場合は, default region を us-east-1 に設定する必要がある.

AWS CDK のインストール

読者のために,執筆時点におけるインストールの手順 (Linux 向け) を簡単に記述する. 将来のバージョンでは変更される可能性があるので,常に 公式のドキュメンテーション で最新の情報をチェックすることを忘れずに.

Node.js がインストールされていれば,基本的に次のコマンドを実行すればよい.

sh
$ sudo npm install -g aws-cdk
$ sudo npm install -g aws-cdk

本書のハンズオンは AWS CDK version 1.100.0 で開発した. CDK は開発途上のライブラリなので,将来的に API が変更される可能性がある. API の変更によりエラーが生じた場合は, version 1.100.0 を使用することを推奨する.

sh
$ npm install -g aws-cdk@1.100
$ npm install -g aws-cdk@1.100

インストールできたか確認するため,次のコマンドを打って正しくバージョンが表示されることを確認する.

sh
$ cdk --version
$ cdk --version

インストールができたら,次のコマンドにより AWS 側の初期設定を行う. これは一度実行すれば OK.

sh
$ cdk bootstrap
$ cdk bootstrap

cdk bootstrap を実行するときは,AWS の認証情報とリージョンが正しく設定されていることを確認する. デフォルトでは ~/.aws/config にあるデフォルトのプロファイルが使用される. デフォルト以外のプロファイルを用いるときは AWS CLI のインストール で紹介したテクニックを使って切り替える.

AWS CDK の認証情報の設定は AWS CLI と基本的に同じである.詳しくは AWS CLI のインストール を参照.

WSL のインストール

本書のハンズオンではコマンドラインから AWS CLI のコマンドを実行したり, Python で書かれたプログラムを実行する. コマンドは基本的に UNIX のターミナルを想定して書かれている. Linux や Mac のユーザーは OS に標準搭載されているターミナルを用いれば良い. Windows を利用している読者は, Windows Subsystem for Linux (WSL) を利用することで,仮想の Linux 環境を構築することを推奨する. Cygwin などの Linux 環境をエミュレートするほかのツールでも構わないが,本書のプログラムは WSL でのみ動作確認を行っている.

WSL とは, Windows の OS 上で Linux の仮想環境を起動するための, Microsoft 社が公式で提供しているソフトウェアである. Ubuntu など希望の Linux distribution が選択でき,基本的にすべての Linux 向けに作られたプログラム・ソフトウェアを使用することができる.

執筆時点では WSL 2 が最新版として提供されているので,以下では WSL 2 のインストール手順を簡単に説明する. 細かな詳細などは, 公式ドキュメンテーション を参照のこと.

前提として,使用される OS は Windows 10 (Pro または Home エディション) でなければならない. さらに,使用している Windows 10 のバージョンが WSL に対応するバージョンであるかを確認する. X64 のシステムでは Version 1903, Build 18362 以上でなければならない. バージョンが対応していない場合は、 Windows のアップデートを行う.

まず最初に, Administrator 権限で PowerShell を起動する (figure_title). 左下の Windows メニューの検索バーに powershell と入力すると, PowerShell のプログラムが見つかるはずである, これを右クリックし、 Run as administrator を選択し起動する.

管理者権限での PowerShell の起動

PowerShell が起動したら、次のコマンドを実行する.

powershell
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

実行して、“The operation completed successfully.” と出力されるのを確認する. これで WSL が enable される.

次に,先ほどと同じ Administrator 権限で開いた PowerShell で次のコマンドを実行する。

powersh
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

実行して, “The operation completed successfully.” と出力されるのを確認する. これが確認出来たら、一度コンピュータを再起動する.

続いて, Linux kernel update package を次のリンクからダウンロードする. https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi

ダウンロードしたファイルをダブルクリックして実行する. ダイアログに従ってインストールを完了させる.

そうしたら,再び PowerShell を開き次のコマンドを実行する。

sh
wsl --set-default-version 2
wsl --set-default-version 2

最後に、自分の好みの Linux distribution をインストールする. ここでは Ubuntu 20.04 をインストールしよう.

Microsoft store のアプリを起動し,検索バーに Ubuntu と入力する. Ubuntu 20.04 LTS という項目が見つかるはずなので,それを開き, “Get” ボタンをクリックする (figure_title). しばらく待つと, Ubuntu 20.04 のインストールが完了する.

Microsoft store から Ubuntu 20.04 をインストール

Ubuntu 20.04 を初回に起動すると,初期設定が自動で開始され,数分待つことになる. 初期設定が終わると,ユーザー名・パスワードを設定するようプロンプトが出るので,プロンプトに従い入力する.

これで WSL2 のインストールが完了した. 早速 WSL2 を起動してみよう. 左下の Windows メニューの検索バーに Ubuntu と入力すると, Ubuntu 20.04 のプログラムが見つかるはずである (figure_title). クリックして起動しよう.

Ubuntu 20.04 の起動

すると,ターミナルの黒い画面が立ち上がるだろう (figure_title). ls, top などのコマンドを打ってみて, WSL がきちんと動作していることを確認しよう.

WSL の起動画面

オプションとして, Windows Terminal というマイクロソフトから提供されているツールを使うと,より快適に WSL を使用することができる. 興味のある読者はこちらのインストールも推奨する.

Docker のインストール

Docker のインストールの方法は OS によって異なる.

Mac ユーザーは, Docker Desktop をインストールする. インストールの方法は, Docker のウェブサイト から, Mac 版の Docker Desktop をダウンロードし,ダウンロードされたファイルをダブルクリックし, Applications のフォルダにドラッグするだけで良い. 詳細は 公式ドキュメンテーション を参照のこと.

Windows のユーザーは,Docker Desktop をインストールする. その際, WSL 2 が事前にインストールされていなければならない. 詳細は 公式ドキュメンテーション を参照のこと. Docker Desktop をインストールすると, WSL からも docker コマンドが使用できるようになる.

Linux ユーザー (特に Ubuntu ユーザー) については,インストールの方法はいくつかのアプローチがある. 公式ドキュメンテーション にいくつかのインストールの方法が示されているので,詳しい情報はそちらを参照いただきたい.

最も簡単な方法は, Docker が公式で提供しているインストールスクリプトを用いる方法である. この場合,次のコマンドを実行することで Docker がインストールされる.

sh
$ curl -fsSL https://get.docker.com -o get-docker.sh
$ sudo sh get-docker.sh
$ curl -fsSL https://get.docker.com -o get-docker.sh
$ sudo sh get-docker.sh

デフォルトのインストールでは, root ユーザーのみが docker コマンドを使用できる設定になっている. 従って,コマンドには毎回 sudo を付け加える必要がある. これが面倒だと感じる場合は,次のステップにより,使用するユーザーを docker というグループに追加する (詳細は 公式ドキュメンテーション "Post-installation steps for Linux" を参照).

まず最初に, docker という名前にグループを追加する. インストールによっては,既に docker グループが作られている場合もある.

sh
$ sudo groupadd docker
$ sudo groupadd docker

次に,現在使用しているユーザーを docker グループに加える.

sh
$ sudo usermod -aG docker $USER
$ sudo usermod -aG docker $USER

ここまでできたら,一度ログアウトし,再度ログインする. これによって,グループの変更がターミナルのセッションに反映される.

設定が正しくできているかを確認するため,次のコマンドを実行してみる.

sh
$ docker run hello-world
$ docker run hello-world

sudo なしでコンテナが実行できたならば,設定は完了である.

Python venv クイックガイド

他人からもらったプログラムで, numpy や scipy のバージョンが違う!などの理由で,プログラムが動かない,という経験をしたことがある人は多いのではないだろうか. もし,自分の計算機の中に一つしか Python 環境がないとすると,プロジェクトを切り替えるごとに正しいバージョンをインストールし直さなければならず,これは大変な手間である.

コードのシェアをよりスムーズにするためには,ライブラリのバージョンはプロジェクトごとに管理されるべきである. それを可能にするのが Python 仮想環境とよばれるツールであり, venv, pyenv, conda などがよく使われる.

そのなかでも, venv は Python に標準搭載されているのでとても便利である. pyenvconda は,別途インストールの必要があるが,それぞれの長所もある.

venv を使って仮想環境を作成するには,

sh
$ python -m venv .env
$ python -m venv .env

と実行する. これにより .env/ というディレクトリが作られ,このディレクトリに依存するライブラリが保存されることになる.

この新たな仮想環境を起動するには

sh
$ source .env/bin/activate
$ source .env/bin/activate

と実行する.

シェルのプロンプトに (.env) という文字が追加されていることを確認しよう (figure_title). これが, "いまあなたは venv の中にいますよ" というしるしになる.

venv を起動したときのプロンプト

仮想環境を起動すると,それ以降実行する pip コマンドは, .env/ 以下にインストールされる.このようにして,プロジェクトごとに使うライブラリのバージョンを切り分けることができる.

Python では requirements.txt というファイルに依存ライブラリを記述するのが一般的な慣例である.他人からもらったプログラムに, requirements.txt が定義されていれば,

sh
$ pip install -r requirements.txt
$ pip install -r requirements.txt

と実行することで,必要なライブラリをインストールし,瞬時に Python 環境を再現することができる.

venv による仮想環境を保存するディレクトリの名前は任意に選べることができるが, .env という名前を用いるのが一般的である.

ハンズオン実行用の Docker image の使い方

ハンズオンを実行するために必要な, Node.js, Python, AWS CDK などがインストールされた Docker image を用意した. これを使用することで,自分のローカルマシンに諸々をインストールする必要なく,すぐにハンズオンのコードが実行できる.

ハンズオンのいくつかのコマンドは Docker の外 = ローカルマシンのリアル環境で実行されなければならない. それらについてはハンズオンの該当箇所に注意書きとして記してある.

Docker イメージは Docker Hub においてある. Docker イメージのビルドファイルは GitHub の docker/Dockerfile にある.

次のコマンドでコンテナを起動する.

sh
$ docker run -it tomomano/labc:latest
$ docker run -it tomomano/labc:latest

初回にコマンドを実行したときのみ,イメージが Docker Hub からダウンロード (pull) される. 二回目以降はローカルにダウンロードされたイメージが使用される.

コンテナが起動すると,次のようなインタラクティブシェルが表示されるはずである (起動時に -it のオプションをつけたのがポイントである).

sh
root@aws-handson:~/programlisting
root@aws-handson:~/programlisting

この状態で ls コマンドを打つと, handson/ というディレクトリがあるはずである. ここに cd する.

sh
$ cd handson
$ cd handson

すると,各ハンズオンごとのディレクトリが見つかるはずである.

あとは,ハンズオンごとにディレクトリを移動し,ハンズオンごとの virtualenv を作成し,スタックのデプロイを行えばよい (プログラムを実行する など参照). ハンズオンごとに使用する依存ライブラリが異なるので,それぞれのハンズオンごとに virtualenv を作成するという設計になっている.

AWS の認証情報を設定することも忘れずに. AWS CLI のインストール で記述したように, AWS_ACCESS_KEY_ID などの環境変数を設定するのが簡単な方法である. あるいは,ローカルマシンの ~/.aws/credentials に認証情報が書き込まれているなら,このディレクトリをコンテナにマウントすることで,同じ認証ファイルをコンテナ内部から参照することが可能である. この選択肢を取る場合は,次のコマンドでコンテナを起動する.

sh
$ docker run -it -v ~/.aws:/root/.aws:ro tomomano/labc:latest
$ docker run -it -v ~/.aws:/root/.aws:ro tomomano/labc:latest

これにより,ローカルマシンの ~/.aws をコンテナの /root/.aws にマウントすることができる. 最後の :ro は read-only を意味する. 大切な認証ファイルが誤って書き換えられてしまわないように, read-only のフラグをつけることをおすすめする.

/root/ がコンテナ環境におけるホームディレクトリである. ここで紹介した認証ファイルをマウントするテクニックは, SSH 鍵をコンテナに渡すときなどにも使える.

ライセンス

本教科書およびハンズオンのソースコードは CC BY-NC-ND 4.0 に従うライセンスで公開しています.

教育など非商用の目的での本教科書の使用や再配布は自由に行うことが可能です. 商用目的で本書の全体またはその一部を無断で転載する行為は,これを固く禁じます.

]]>
はじめに!

本書の目的・内容

本書は,東京大学計数工学科で 2021 年度 S1/S2 タームに開講されている"システム情報工学特論"の講義資料として作成された.

本書の目的は,クラウドの初心者を対象とし,クラウドの基礎的な知識・概念を解説する. また, Amazon Web Services (以下, AWS) の提供するクラウド環境を実例として,具体的なクラウドの利用方法をハンズオンを通して学ぶ.

とくに,科学・エンジニアリングの学生を対象として,研究などの目的でクラウドを利用するための実践的な手順を紹介する. 知識・理論の説明は最小限に留め,実践を行う中で必要な概念の解説を行う予定である. 読者が今後,研究などでクラウドを利用する際の,足がかりとなれば本書の目的は十分達成されたことになる.

本書は以下のような三部構成になっている.

本書の構成
テーマハンズオン

第一部 (1章-4章)

クラウドの基礎

  • AWSに自分のサーバーを立ち上げる

第二部 (5章-9章)

クラウドを活用した機械学習

  • AWS と Jupyter を使って始めるディープラーニング

  • スケーラブルな自動質問回答ボットを作る

  • 並列化されたハイパーパラメータサーチの実装

第三部 (10章-13章)

サーバーレスアーキテクチャ入門

  • Lambda, DynamoDB, S3 の演習

  • 俳句を投稿する SNS "Bashoutter" を作る

第一部は,クラウドの基礎となる概念・知識を解説する. セキュリティやネットワークなど,クラウドを利用する上で最低限おさえなければいけないポイントを説明する. ハンズオンでは,はじめての仮想サーバーを AWS に立ち上げる演習を行う.

第二部では,クラウド上で科学計算 (とくに機械学習) を走らせるための入門となる知識・技術を解説する. あわせて, Docker とよばれる仮想計算環境の使用方法を紹介する. 一つ目のハンズオンでは, AWS のクラウドで Jupyter Notebook を起動し簡単な機械学習の計算を走らせる課題を実践する. 二つ目のハンズオンでは,深層学習を用いた自然言語処理により,質問に自動で回答を生成するボットを作成する. 最後に,複数台の GPU インスタンスからなるクラスターを起動し,並列に深層学習のハイパーパラメータサーチを行う方法を紹介する.

第三部では,サーバーレスアーキテクチャとよばれる最新のクラウドのアーキテクチャを紹介する. これは,サーバーの処理能力を負荷に応じてより柔軟に拡大・縮小するための概念であり,それ以前 (Serverful としばしばよばれる) と質的に異なる設計思想をクラウドに導入するものである. ハンズオンでは,サーバーレスクラウドの主要なコンポーネントである Lambda, DynamoDB, S3 の演習を提供する. さらに,サーバーレスの技術を使用して簡単な SNS をクラウド上に作成する.

これらの豊富なハンズオンにより, AWS 上にクラウドシステムを開発するための知識と技術が身につくはずである. いずれのハンズオンも,実用性を重視したものになっており,これらをベースにカスタマイズを施すことで様々な応用が可能である.

本書のフィロソフィー

本書のフィロソフィーを一言で表すなら, "ロケットで宇宙まで飛んでいって一度地球を眺めてみよう!" である.

どういうことか?

ここでいう"地球"とは,クラウドコンピューティングの全体像のことである. 言うまでもなく,クラウドという技術は非常に広範かつ複雑な概念で,幾多の情報技術・ハードウェア・アルゴリズムが精緻に組み合わさってできた総体である. そして,今日では科学研究から日常のインフラ設備に至るまで,我々の社会の多くの部分がクラウド技術によって支えられている.

ここでいう"ロケット"とはこの講義のことである. この講義では,ロケットに乗って宇宙まで飛び立ち,地球(クラウド)の全体を自身の目で眺めてもらう. その際,ロケットの成り立ちや仕組み (背後にある要素技術やプログラムのソースコード) を深くは問わない. 将来,自分が研究などの目的でクラウドを利用することになった際に,改めて学んでもらえば良い. 本書の目的はむしろ,クラウドの最先端に実際に触れ,そこからどんな景色が見えるか(どんな応用が可能か)を実感してもらうことである.

そのような理由で,本書はクラウドの基礎から応用まで幅広いテーマを取り扱う. 第一部はクラウドの基礎から始め,第二部では一気にレベルアップし機械学習(深層学習)をクラウドで実行する手法を解説する. さらに第三部では,サーバーレス・アーキテクチャというここ数年のうちに確立した全く新しいクラウドの設計について解説する. それぞれで本一冊分以上の内容に相当するものであるが,本書はあえてこれらを一冊にまとめ連続的に俯瞰するという野心的な意図をもって執筆された.

決して楽な搭乗体験ではないかもしれないが,このロケットにしがみついてきてもらえれば,とてもエキサイティングな景色が見られることを約束したい.

宇宙からみた地球 (Image from NASA https://www.nasa.gov/image-feature/planet-of-clouds)

AWS アカウント

本書では,ハンズオン形式で AWS のクラウドを実際に動かす演習を提供する. 自分でハンズオンを実行してみたい読者は,各自で AWS のアカウントの作成をしていただく. AWS のアカウントの作成の仕方は巻末付録 (AWS アカウントの取得) に簡単に記載したので,必要に応じて参照していただきたい.

AWS にはいくつかの機能に対して無料利用枠が設定されており,いくつかのハンズオンは無料の範囲内で実行できる. 一方,ほかのハンズオン (とくに機械学習を扱うもの) では数ドル程度のコストが発生する. ハンズオンごとに発生するおおよそのコストについて記述があるので,注意をしながらハンズオンに取り組んでいただきたい.

また,大学などの教育機関における講義で AWS を使用する際は, AWS Educate というプログラムを利用することも可能である. これは,講義の担当者が申請を行うことで,受講する学生に対し AWS クレジットが提供されるというプログラムである. AWS Educate を利用することで金銭的な負担なしに AWS を体験することができる. また,講義を経由せず個人でも AWS Educate に参加することも可能である. AWS Educate からは様々な学習教材が提供されているので,ぜひ活用してもらいたい.

環境構築

本書では, AWS 上にクラウドアプリケーションを展開するハンズオンを実施する. そこで紹介するプログラムを実行するためには,以下の計算機環境が必要である. インストールの方法については,巻末付録 (Appendix: 環境構築) に記してある. 必要に応じて参照し,環境構築を各自実施していただきたい.

  • UNIX 系コンソール: ハンズオンで紹介するコマンドを実行したり, SSH でサーバーにアクセスするため, UNIX 系のコンソール環境が必要である. Mac または Linux のユーザーは, OS に標準搭載のコンソール(ターミナルとも呼ばれる)を使用すればよい. Windows のユーザーは, Windows Subsystem for Linux (WSL) を使い, Linux の仮想環境のインストールを推奨する (WSL のインストール 参照).

  • Docker: 本書では Docker とよばれる仮想計算環境の利用方法を解説する. インストール手順については Docker のインストール を参照のこと.

  • Python: Version 3.6 以上をインストールする. とくに,ハンズオンでは venv モジュールを使用する. venv の使い方は Python クイックガイド 参照のこと.

  • Node.js: version 12.0 以上 をインストールする.

  • AWS CLI: Version 2 をインストールする. インストール手順については AWS CLI のインストール 参照のこと.

  • AWS CDK: Version 1.100 以上をインストールする. Version 2 以降には未対応である. インストール手順については AWS CDK のインストール 参照のこと.

  • AWS 認証鍵の設定: AWS API をコマンドラインから呼ぶには,認証鍵 (secret key) が設定されている必要がある. 認証鍵の設定については AWS CLI のインストール 参照のこと.

ハンズオン実行用の Docker Image

Python, Node.js, AWS CDK など,ハンズオンのプログラムを実行するために必要なプログラム/ライブラリがインストール済みの Docker image を用意した. また,ハンズオンのソースコードもクローン済みである. Docker の使い方を知っている読者は,これを使えば,諸々のインストールをする必要なく,すぐにハンズオンのプログラムを実行できる.

次のコマンドで起動する.

sh
$ docker run -it tomomano/labc
$ docker run -it tomomano/labc

この Docker image の使い方や詳細は ハンズオン実行用の Docker image の使い方 に記載している.

前提知識

本書を読むにあたり,要求する前提知識は大学初等程度の計算機科学の知識 (OS,プログラミングなど)のみである. それ以上の前提知識はとくに仮定しない. クラウドの利用経験もゼロで問題ない. が,以下の事前知識があるとよりスムーズに理解をすることができるだろう.

  • Python の基本的な理解: 本書では Python を使ってプログラムの作成を行う. 使用するライブラリは十分抽象化されており,関数の名前を見ただけで意味が明瞭なものがほとんどであるので, Python に詳しくなくても心配する必要はない.

  • Linux コマンドラインの基礎的な理解: クラウドを利用する際,クラウド上に立ち上がるサーバーは基本的に Linux である. Linux のコマンドラインについて知識があると,トラブルシュートなどが容易になる. 筆者のおすすめの参考書は The Linux Command Line by William Shotts である. ウェブで無料で読むことができるので,読んだことのない人はぜひ一読を.

講義に関連する資料

ハンズオンで使うプログラムや教科書のソースコードは以下のウェブページで公開している.

https://github.com/tomomano/learn-aws-by-coding

本書で使用するノーテーションなど

  • コードやシェルのコマンドは monospace letter で記述する.

  • シェルに入力するコマンドは,それがシェルコマンドであると明示する目的で,先頭に $ がつけてある. $ はコマンドをコピー&ペーストするときは除かなければならない. 逆に,コマンドの出力には $ はついていない点に留意する.

また,以下のような形式で注意やチップスを提供する.

追加のコメントなどを記す.

発展的な議論やアイディアなどを紹介する.

陥りやすいミスなどの注意事項を述べる.

絶対に犯してはならないミスを指摘する.

クラウド概論

クラウドとは?

Cloud

クラウドとはなにか? クラウドという言葉は,それ自身がとても広い意味をもつので,厳密な定義付けを行うことは難しい.

学術的な意味でのクラウドの定義づけをするとしたら,NIST(米国・国立標準技術研究所) による The NIST Definition of Cloud Computing が引用されることが多い. ここに記載されたクラウドの定義・モデルを図示したのが figure_title である.

The NIST Definition of Cloud Computing

これによると,クラウドとは以下の要件が満たされたハードウェア/ソフトウェアの総体のことをいう.

  • On-demand self-service 利用者のリクエストに応じて計算資源が自動的に割り当てられる.

  • Broad network access 利用者はネットワークを通じてクラウドにアクセスできる.

  • Resource pooling クラウドプロバイダーは,所有する計算資源を分割することで複数の利用者に計算資源を割り当てる.

  • Rapid elasticity 利用者のリクエストに応じて,迅速に計算資源の拡大あるいは縮小を行うことができる.

  • Measured service 計算資源の利用量を計測・監視することができる.

…と,いわれても抽象的でよくわからないかもしれない.もう少し具体的な話をする.

個人が所有する計算機で, CPU をアップグレードしようと思ったら,物理的に筐体を開け,CPU ソケットを露出させ,新しい CPU に交換する必要があるだろう. あるいは,ストレージがいっぱいになってしまったら,古いディスクを抜き取り,新しいディスクを挿入する必要がある. 計算機の場所を移動させたときには,新しい部屋の LAN ケーブルを差し込まないとネットワークには接続できない.

クラウドでは,これらの操作がプログラムからのコマンドによって実行できる. CPU が 1000 個欲しいと思ったならば,そのようにクラウドプロバイダーにリクエストを送れば良い. すると,数分もしないうちに 1000 CPU の計算資源が割り当てられる. ストレージを 1TB から 10TB に拡張しようと思ったならば,そのようにコマンドを送ればよい (これは,Google Drive や Dropbox などのサービスなどで馴染みのある人も多いだろう). 計算資源を使い終わったら,そのことをプロバイダーに伝えれば,割り当て分はすぐさま削除される. クラウドプロバイダーは,使った計算資源の量を正確にモニタリングしており,その量をもとに利用料金の計算が行われる.

このように,クラウドの本質は物理的なハードウェアの仮想化・抽象化であり,利用者はコマンドを通じて,まるでソフトウェアの一部かのように,物理的なハードウェアの管理・運用を行うことができる. もちろん,背後では,データセンターに置かれた膨大な数の計算機が大量の電力を消費しながら稼働している. クラウドプロバイダーはデータセンターの計算資源を上手にやりくりし,ソフトウェアとしてのインターフェースをユーザーに提供することで,このような仮想化・抽象化を達成しているわけである. クラウドプロバイダーの視点からすると,大勢のユーザーに計算機を貸し出し,データセンターの稼働率を常時 100%に近づけることで,利益率の最大化を図っているのである.

著者の言葉で,クラウドの重要な特性を定義するならば,以下のようになる.

クラウドとは計算機ハードウェアの抽象化である.つまり,物理的なハードウェアをソフトウェアの一部かのように自在に操作・拡大・接続することを可能にする技術である.

先述の The NIST Definition of Cloud Computing に戻ると,クラウドプロバイダーによるクラウドサービスの形態としては,次の三つが定義されている (figure_title).

  • Software as a Service (SaaS): クラウド上で実行されるアプリケーションをサービスとして利用者に提供する形態. 例として, Google Drive や Slack などが挙げられる. 利用者は,背後にあるクラウドのインフラ (ネットワークやサーバーなど) には直接触れず,アプリケーションとして提供されているクラウドサービスを享受する.

  • Platform as a Service (PaaS): 顧客の作成したアプリケーション (多くの場合データベースと API リクエスト処理を行うサーバーのコードから構成される) をデプロイする環境をサービスとして利用者に提供する形態. PaaS では利用者はクラウドのインフラに直接触れることはなく,計算負荷が増減した際のサーバーのスケーリングはクラウドプロバイダーによってなされる. 例としては, Google App Engine や Heroku などがある.

  • Infrastructure as a Service (IaaS): クラウド上の計算インフラストラクチャーを従量課金制で利用者に提供する形態. 利用者は必要なネットワーク・サーバー・ストレージをプロバイダーから借り受け,そこに自身のアプリケーションを展開し運用する. IaaS の例としては AWS EC2 などが挙げられる.

本書が扱うのは,主に IaaS におけるクラウド開発である. すなわち,開発者がクラウドのインフラを直接操作し,所望のネットワーク・サーバー・ストレージなどを一から構成し,そこにアプリケーションを展開するというクラウド開発である. この意味において,クラウドの開発とはクラウドインフラストラクチャーを定義・展開するプログラムを構築するステップインフラ上で実際に走るアプリケーションを作成するステップの二つに分けることができる. この二つは,プログラマーの技術としてはある程度分業を行うことが可能であるが,最も効率化・最適化されたクラウドシステムを構築するためには両方の理解が必須である. 本書では,前者 (クラウドインフラの記述) に重きを置きつつ,アプリケーションレイヤーの話題も取り扱う. PaaS とは,開発者はアプリケーションレイヤーの開発に注力し,クラウドインフラの部分はクラウドプロバイダーに依存するという概念である. PaaS は,クラウドインフラの開発が不要になることで開発の時間が短縮されるが,細かなインフラの挙動はコントロールできないという限界がある. 本書では PaaS についてはとくに取り扱わない.

SaaS は本書の文脈では開発による"成果物"と捉えられるだろう. すなわち, IaaS を構成するプログラムを作成し展開することによって,一般の人が利用できるようなウェブ上の計算サービスやデータベースを提供することが開発の最終ゴールである. 本書のハンズオンではその実例として,シンプルな SNS の作成 (Hands-on #6: Bashoutter) などの演習を提供する.

なお,最近では Function as a Service (FaaS) やサーバーレスコンピューティングなども新たなクラウドのカテゴリとして認知されている. これらの概念については Hands-on #5: サーバーレス入門 などの章で詳しく触れていく. 本書を読み進める中で明らかになるように,クラウドの技術は日進月歩である. 本書では実用的・教育的な観点から,従来的なクラウドの設計概念に触れたあと,サーバーレスなどの最新の技術も網羅するので,楽しみにしながら読み進めていただきたい.

最後に,The NIST Definition of Cloud Computing によると,クラウドの運用形態について次のような定義がなされている (figure_title). 特定の組織・団体・企業の内部のみで使用されるクラウドを,プライベートクラウド (private cloud) とよぶ. 例えば,大学や研究機関では,その機関の構成員向けの大規模計算機サーバーが運用されていることが多い. プライベートクラウドは,組織の構成員ならば無料もしくは極めて割安のコストで計算を実行できる. しかし,使用できる計算資源の上限は限られる場合が多く,拡張時の柔軟性に欠ける場合もある.

一方,商用のサービスとして一般の顧客に向けたクラウドのことを,パブリッククラウド (public cloud) とよぶ. 有名なパブリッククラウドプラットフォームの例を挙げると, Google 社が提供する Google Cloud Platform (GCP), Microsoft 社が提供する Azure, Amazon 社が提供する Amazon Web Services (AWS) などがある. パブリッククラウドを利用する場合は,プロバイダーの設定した利用料金を支払うことになる. その分,巨大なデータセンターを運用する企業の計算資源にアクセスすることができるので,計算のキャパシティは無尽蔵にあるといって過言でない.

第三のクラウドの運用形態として,コミュニティクラウド (community cloud) が挙げられる. これは,例えば政府の省庁・機関など目的・役割を共有する団体・組織が共有して運用するクラウドを指す. 最後に,ハイブリッドクラウド (hybrid cloud) という形態もあり,これはプライベート・パブリック・コミュニティクラウドの二つ以上の組み合わせによって構成されるクラウドのことである. データ保護の観点から,いくつかの機密データやプライバシーに関わる情報はプライベートクラウドに保持し,残りのシステムをパブリッククラウドに依存する,などの形態が想定される.

本書で説明するのは,基本的にパブリッククラウドを使ったクラウド開発である. 特に,Amazon Web Services (AWS) を使用して,具体的な技術と概念を学んでいく. 一方で,サーバーのスケーリングや仮想計算環境などのテクニックはすべてのクラウドに共通な概念であるので,クラウドのプラットフォームが変わろうと一般に通用する知識も同時に身につくはずだ.

なぜクラウドを使うのか?

上述のように,クラウドとはプログラムを通じて自由に計算資源を操作することのできる計算環境である. ここでは,リアルなローカル計算環境と比べて,なぜクラウドを使うと良いことがあるのかについて述べたい.

  1. 自由にサーバーのサイズをスケールできる

    なにか新しいプロジェクトを始めるとき,あらかじめ必要なサーバーのスペックを知るのは難しい. いきなり大きなサーバーを買うのはリスクが高い. 一方で,小さすぎるサーバーでは,後のアップグレードが面倒である. クラウドを利用すれば,プロジェクトを進めながら,必要な分だけの計算資源を確保することができる. 2. 自分でサーバーをメンテナンスする必要がない

    悲しいことに,コンピュータとは古くなるものである.最近の技術の進歩の速度からすると,5 年も経てば,もはや当時の最新コンピュータも化石と同じである. 5 年ごとにサーバーを入れ替えるのは相当な手間である. またサーバーの停電や故障など不意の障害への対応も必要である. クラウドでは,そのようなインフラの整備やメンテナンスはプロバイダーが自動でやってくれるので,ユーザーが心配する必要がない. 3. 初期コスト 0

    自前の計算環境とクラウドの,経済的なコストのイメージを示したのが figure_title である. クラウドを利用する場合の初期コストは基本的に 0 である. その後,使った利用量に応じてコストが増大していく. 一方,自前の計算環境では,大きな初期コストが生じる. その分,初期投資後のコストの増加は,電気利用料やサーバー維持費などに留まるため,クラウドを利用した場合よりも傾きは小さくなる. 自前の計算機では,ある一定期間後,サーバーのアップグレードなどによる支出が生じることがある. 一方,クラウドを利用する場合は,そのような非連続なコストの増大は基本的に生じない. クラウドのコストのカーブが,自前計算環境のコストのカーブの下にある範囲においては,クラウドを使うことは経済的なコスト削減につながる.

    クラウドと自前計算機環境の経済的コストの比較

とくに,**1.**の点は研究の場面では重要であると筆者は感じる. 研究をやっていて,四六時中計算を走らせ続けるという場合は少ない. むしろ,新しいアルゴリズムが完成したとき・新しいデータが届いたとき,集中的・突発的に計算タスクが増大することが多いだろう. そういったときに,フレキシブルに計算力を増強させることができるのは,クラウドを使う大きなメリットである.

ここまでクラウドを使うメリットを述べたが,逆に,デメリットというのも当然存在する.

  1. クラウドは賢く使わないといけない

    figure_title で示したコストのカーブにあるとおり,使い方によっては自前の計算環境のほうがコスト的に有利な場面は存在しうる. クラウドを利用する際は,使い終わった計算資源はすぐに削除するなど,利用者が賢く管理を行う必要があり,これを怠ると思いもしない額の請求が届く可能性がある. 2. セキュリティ

    クラウドは,インターネットを通じて世界のどこからでもアクセスできる状態にあり,セキュリティ管理を怠ると簡単にハッキングの対象となりうる. ハッキングを受けると,情報流出だけでなく,経済的な損失を被る可能性がある. 3. ラーニングカーブ

    上記のように,コスト・セキュリティなど,クラウドを利用する際に留意しなければならない点は多い. 賢くクラウドを使うには,十分なクラウドの理解が必要であり,そのラーニングカーブを乗り越える必要がある.

Mac/Linux などでコマンドを入力するときに使用する,あの黒い画面のことを Terminal とよんだりする. この言葉の語源をご存知だろうか?

Terminal

この言葉の語源は,コンピュータが誕生して間もない頃の時代に遡る. その頃のコンピュータというと,何千何万のという数の真空管が接続された,会議室一個分くらいのサイズのマシンであった. そのような高価でメンテが大変な機材であるから,当然みんなでシェアして使うことが前提となる. ユーザーがコンピュータにアクセスするため,マシンからは何本かのケーブルが伸び,それぞれにキーボードとスクリーンが接続されていた… これを Terminal とよんでいたのである. 人々は,代わる代わる Terminal の前に座って,計算機との対話を行っていた.

時代は流れ,Windows や Mac などのいわゆるパーソナルコンピュータの出現により,コンピュータはみんなで共有するものではなく,個人が所有するものになった.

最近のクラウドの台頭は,みんなで大きなコンピュータをシェアするという,最初のコンピュータの使われ方に原点回帰していると捉えることもできる. 一方で,スマートフォンやウェアラブルなどのエッジデバイスの普及も盛んであり,個人が複数の"小さな"コンピュータを所有する,という流れも同時に進行しているのである.

AWS 入門

AWS とは?

本書では,クラウドの実践を行うプラットフォームとして, AWS を用いる. 実践にあたって,最低限必要な AWS の知識を本章では解説しよう.

AWS (Amazon Web Services) は Amazon 社が提供する総合的なクラウドプラットフォームである. AWS は Amazon 社が持つ膨大な計算リソースを貸し出すクラウドサービスとして,2006 年に誕生した. 2021 年では,クラウドプロバイダーとして最大のマーケットシェア (約 32%) を保持している (参照). Netflix や Slack をはじめとした多くのウェブ関連のサービスで,一部または全てのサーバーリソースが AWS から提供されているとのことである. よって,知らないうちに AWS の恩恵にあずかっている人も少なくないはずだ.

最大のシェアをもつだけに,機能・サービスの幅広さはほかのクラウドプラットフォームと比べ抜きんでている. また,利用者数が多いことを反映して,公式あるいはサードパーティによる技術紹介記事が数多くウェブ上に存在しているだけでなく,ライブラリのユーザーコミュニティも大きく問題解決が捗るのも魅力の一つだ. 初期のころウェブビジネスを行う企業がユーザーの大半を占めていたが,最近は大学などでの科学研究用途としても頻繁に用いられるようになってきている.

AWS の機能・サービス

figure_title は,執筆時点において AWS で提供されている主要な機能・サービスの一覧である.

AWSで提供されている主要なサービス一覧

計算,ストレージ,データベース,ネットワーク,セキュリティなど,クラウドの構築に必要な様々な要素が独立したコンポーネントとして提供されている. 基本的に,これらを組み合わせることで一つのクラウドシステムができあがる.

また,機械学習・音声認識・AR/VR など,特定のアプリケーションにパッケージ済みのサービスも提供されている. これらを合計すると全部で 170 個以上のサービスが提供されているとのことである (参照).

AWS の初心者が陥りがちなのは,大量のサービスの数に圧倒され,どこから手をつけたらよいのかわからなくなる,という状況である. たくさんのサービスの中から,どのサービスをどの順番で学んでいったらいいのか,その道筋すら明らかでなく,大きな参入障壁となっていることは間違いない. だが実のところ, AWS の基本的な構成要素はそのうちの数個のみに限られる. 基本要素となる機能の使い方を知れば, AWS のおおよそのリソースを使いこなすことが可能になる. ほかの機能の多くは,基本の要素を組み合わせて特定のアプリケーションに特化したパッケージとして AWS が用意したものである. そのポイントを認知することが, AWS の学習の最初のステップである.

ここでは, AWS 上でクラウドシステムを構築するときの基本となる構成要素を列挙する. これらは後のハンズオンで実際にプログラムを書きながら体験する. 現時点では,名前だけでも頭の片隅に記憶してもらえればよい.

計算

S3 EC2 (Elastic Compute Cloud) 様々なスペックの仮想マシンを作成し,計算を実行することができる. クラウドの最も基本となる構成要素である. Hands-on #1: 初めての EC2 インスタンスを起動する, Hands-on #2: AWS でディープラーニングを実践, Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する で詳しく触れる.

S3 Lambda Function as a Service (FaaS) とよばれる,小さな計算をサーバーなしで実行するためのサービス. サーバーレスアーキテクチャの章 (Serverless architecture) で詳しく解説する.

ストレージ

S3 EBS (Elastic Block Store) EC2 に付与することのできる仮想データドライブ. いわゆる"普通の"(一般的な OS で使われている)ファイルシステムを思い浮かべてくれたらよい.

S3 S3 (Simple Storage Service) Object Storage とよばれる,API を使ってデータの読み書きを行う,いうなれば”クラウド・ネイティブ”なデータの格納システムである. サーバーレスアーキテクチャの章 (Serverless architecture) で詳しく解説する.

データベース

S3 DynamoDB NoSQL 型のデータベースサービス (知っている人は mongoDB などを思い浮かべたらよい). サーバーレスアーキテクチャの章 (Serverless architecture) で詳しく解説する.

ネットワーク

S3 VPC(Virtual Private Cloud) AWS 上に仮想ネットワーク環境を作成し,仮想サーバー間の接続を定義したり,外部からのアクセスなどを管理する. EC2 は VPC の内部に配置されなければならない.

API Gateway S3 API のエンドポイントとバックエンドのサービス (Lambda など) を接続する際に用いる,リバースプロキシとしての役割を担う. Hands-on #6: Bashoutter で詳しく解説する.

Region と Availability Zone

AWS を使用する際に知っておかなければならない重要な概念として, リージョン (Region)Availability Zone (AZ) がある (figure_title). 以下ではこの概念について簡単に記述する.

AWSにおける Region と Availability Zones

リージョン (Region) とは,おおまかに言うとデータセンターの所在地のことである. 執筆時点において, AWS は世界の 25 の国と地域でデータセンターを所有している. figure_title は執筆時点で利用できるリージョンの世界地図を示している. 日本では東京と大阪にデータセンターがある. 各リージョンには固有の ID がついており,例えば東京は ap-northeast-1, 米国オハイオ州は us-east-2,などと定義されている.

Regions in AWS(出典: https://aws.amazon.com/about-aws/global-infrastructure/)

AWS コンソールにログインすると,画面右上のメニューバーでリージョンを選択することができる(figure_title, 赤丸で囲った箇所). EC2, S3 などの AWS のリソースは,リージョンごとに完全に独立である. したがって,リソースを新たにデプロイする際,あるいはデプロイ済みのリソースを閲覧する際は,コンソールのリージョンが正しく設定されているか,確認する必要がある. ウェブビジネスを展開する場合などは,世界の各地にクラウドを展開する必要があるが,個人的な研究用途として用いる場合は,最寄りのリージョン (i.e. 東京) を使えば基本的に問題ない.

AWSコンソールでリージョンを選択

Avaialibity Zone (AZ) とは,リージョン内で地理的に隔離されたデータセンターのことである. それぞれのリージョンは 2 個以上の AZ を有しており,もし一つの AZ で火災や停電などが起きた場合でも,ほかの AZ がその障害をカバーすることができる. また, AZ 間は高速な AWS 専用ネットワーク回線で結ばれているため, AZ 間のデータ転送は極めて早い. AZ は,ビジネスなどでサーバーダウンが許容されない場合などに注意すべき概念であり,個人的な用途で使う限りにおいてはあまり深く考慮する必要はない.言葉の意味だけ知っておけば十分である.

AWS を使用する際,どこのリージョンを指定するのがよいのだろうか? インターネットの接続速度の観点からは,地理的に一番近いリージョンを使用するのが一般的によいだろう. 一方, EC2 の利用料などはリージョンごとに価格設定が若干 (10-20%程度) 異なる. したがって,自分が最も頻繁に利用するサービスの価格が最も安く設定されているリージョンを選択する,というのも重要な視点である. また,いくつかのサービスは,特定のリージョンで利用できない場合もある. これらのポイントから総合的に判断して使用するリージョンを決めると良い.

AWS Educate を利用している読者へ

執筆時点において,AWS Educate による Starter Account を使用している場合は us-east-1 region のみ利用できる (参照).

AWS でのクラウド開発

AWS のクラウドの全体像がわかってきたところで,次のトピックとして,どのようにして AWS 上にクラウドの開発を行い,展開していくかについての概略を解説しよう.

AWS のリソースを追加・編集・削除するなどの操作を実行するには,コンソールを用いる方法と,API を用いる方法の,二つの経路がある.

コンソール画面からリソースを操作する

AWS のアカウントにログインすると,まず最初に表示されるのがAWS コンソールである (figure_title).

AWSマネージメントコンソール画面

コンソールを使うことで, EC2 のインスタンスを立ち上げたり,S3 のデータを追加・削除したり,ログを閲覧したりなど,AWS 上のあらゆるリソースの操作を GUI (Graphical User Interface) を通して実行することができる. 初めて触る機能をポチポチと試したり,デバッグを行うときなどにとても便利である

コンソールはさらっと機能を試したり,開発中のクラウドのデバッグをするときには便利なのであるが,実際にクラウドの開発をする場面でこれを直接いじることはあまりない. むしろ,次に紹介する API を使用して,プログラムとしてクラウドのリソースを記述することで開発を行うのが一般的である. そのような理由で,本書では AWS コンソールを使った AWS の使い方はあまり触れない. AWS のドキュメンテーションには,たくさんの チュートリアル が用意されており,コンソール画面から様々な操作を行う方法が記述されているので,興味がある読者はそちらを参照されたい.

API からリソースを操作する

API (Application Programming Interface) を使うことで,コマンドを AWS に送信し,クラウドのリソースの操作をすることができる. API とは,端的に言えば AWS が公開しているコマンドの一覧であり,GET, POST, DELETE などの REST API から構成されている (REST API については REST API で簡単に解説する). が,直接 REST API を入力するのは面倒であるので,その手間を解消するための様々なツールが提供されている.

例えば, AWS CLI は, UNIX コンソールから AWS API を実行するための CLI (Command Line Interface) である. CLI に加えて,いろいろなプログラミング言語での SDK (Software Development Kit) が提供されている.以下に一例を挙げる.

具体的な API の使用例を見てみよう.

S3 に新しい保存領域 (Bucket (バケット) とよばれる) を追加したいとしよう. AWS CLI を使った場合は,次のようなコマンドを打てばよい.

sh
$ aws s3 mb s3://my-bucket --region ap-northeast-1
$ aws s3 mb s3://my-bucket --region ap-northeast-1

上記のコマンドは, my-bucket という名前のバケットを, ap-northeast-1 のリージョンに作成する.

Python からこれと同じ操作を実行するには, boto3 ライブラリを使って,次のようなスクリプトを実行する.

python
import boto3

s3_client = boto3.client("s3", region_name="ap-northeast-1")
s3_client.create_bucket(Bucket="my-bucket")
import boto3

s3_client = boto3.client("s3", region_name="ap-northeast-1")
s3_client.create_bucket(Bucket="my-bucket")

もう一つ例をあげよう.

新しい EC2 のインスタンス(インスタンスとは,起動状態にある仮想サーバーの意味である)を起動するには,次のようなコマンドを打てば良い.

sh
$ aws ec2 run-instances --image-id ami-xxxxxxxx --count 1 --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-903004f8 --subnet-id subnet-6e7f829e
$ aws ec2 run-instances --image-id ami-xxxxxxxx --count 1 --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-903004f8 --subnet-id subnet-6e7f829e

このコマンドにより, t2.micro というタイプ (1 vCPU, 1.0 GB RAM) のインスタンスが起動する. ここではその他のパラメータの詳細の説明は省略する (ハンズオン (Hands-on #1: 初めての EC2 インスタンスを起動する) で詳しく解説する).

Python から上記と同じ操作を実行するには,以下のようなスクリプトを使う.

python
import boto3

ec2_client = boto3.client("ec2")
ec2_client.run_instances(
    ImageId="ami-xxxxxxxxx",
    MinCount=1,
    MaxCount=1,
    KeyName="MyKeyPair",
    InstanceType="t2.micro",
    SecurityGroupIds=["sg-903004f8"],
    SubnetId="subnet-6e7f829e",
)
import boto3

ec2_client = boto3.client("ec2")
ec2_client.run_instances(
    ImageId="ami-xxxxxxxxx",
    MinCount=1,
    MaxCount=1,
    KeyName="MyKeyPair",
    InstanceType="t2.micro",
    SecurityGroupIds=["sg-903004f8"],
    SubnetId="subnet-6e7f829e",
)

以上の例を通じて,API によるクラウドのリソースの操作のイメージがつかめてきただろうか? コマンド一つで,新しい仮想サーバーを起動したり,データの保存領域を追加したり,任意の操作を実行できるわけである. 基本的に,このようなコマンドを複数組み合わせていくことで,自分の望む CPU・RAM・ネットワーク・ストレージが備わった計算環境を構築することができる. もちろん,逆の操作 (リソースの削除) も API を使って実行できる.

ミニ・ハンズオン: AWS CLI を使ってみよう

ここでは,ミニ・ハンズオンとして,AWS CLI を実際に使ってみる. AWS CLI は先述のとおり, AWS 上の任意のリソースの操作が可能であるが,ここでは一番シンプルな,S3 を使ったファイルの読み書きを実践する (EC2 の操作は少し複雑なので,第一回ハンズオンで行う). aws s3 コマンドの詳しい使い方は 公式ドキュメンテーションを参照.

AWS CLI のインストールについては, AWS CLI のインストール を参照.

以下に紹介するハンズオンは,基本的に S3 の無料枠 の範囲内で実行することができる.

以下のコマンドを実行する前に,AWS の認証情報が正しく設定されていることを確認する. これには ~/.aws/credentials のファイルに設定が書き込まれているか,環境変数 (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION) が定義されている必要がある. 詳しくは AWS CLI のインストール を参照.

まずは,S3 にデータの格納領域 (Bucket とよばれる.一般的な OS での"ドライブ"に相当する) を作成するところから始めよう.

sh
$ bucketName="mybucket-$(openssl rand -hex 12)"
$ echo $bucketName
$ aws s3 mb "s3://${bucketName}"
$ bucketName="mybucket-$(openssl rand -hex 12)"
$ echo $bucketName
$ aws s3 mb "s3://${bucketName}"

S3 のバケットの名前は, AWS 全体で一意的でなければならないことから,前述のコマンドではランダムな文字列を含んだバケットの名前を生成し,bucketName という変数に格納している. そして, aws s3 mb (mb は make bucket の略) によって,新しいバケットを作成する.

次に,バケットの一覧を取得してみよう.

sh
$ aws s3 ls

2020-06-07 23:45:44 mybucket-c6f93855550a72b5b66f5efe
$ aws s3 ls

2020-06-07 23:45:44 mybucket-c6f93855550a72b5b66f5efe

先ほど作成したバケットがリストにあることを確認できる.

本書のノーテーションとして,コマンドラインに入力するコマンドは,それがコマンドであると明示する目的で先頭に $ がつけてある. $ はコマンドをコピー&ペーストするときは除かなければならない. 逆に,コマンドの出力は $ なしで表示されている.

次に,バケットにファイルをアップロードする.

sh
$ echo "Hello world" > hello_world.txt
$ aws s3 cp hello_world.txt "s3://${bucketName}/hello_world.txt"
$ echo "Hello world" > hello_world.txt
$ aws s3 cp hello_world.txt "s3://${bucketName}/hello_world.txt"

上では hello_world.txt というダミーのファイルを作成して,それをアップロードした.

それでは,バケットの中にあるファイルの一覧を取得してみる.

sh
$ aws s3 ls "s3://${bucketName}" --human-readable

2020-06-07 23:54:19   13 Bytes hello_world.txt
$ aws s3 ls "s3://${bucketName}" --human-readable

2020-06-07 23:54:19   13 Bytes hello_world.txt

先ほどアップロードしたファイルがたしかに存在することがわかる.

最後に,使い終わったバケットを削除する.

sh
$ aws s3 rb "s3://${bucketName}" --force
$ aws s3 rb "s3://${bucketName}" --force

rb は remove bucket の略である. デフォルトでは,バケットの中にファイルが存在すると削除できない. 空でないバケットを強制的に削除するには --force のオプションを付ける.

以上のように,AWS CLI を使って S3 バケットに対しての一連の操作を実行できた. EC2 や Lambda, DynamoDB などについても同様に AWS CLI を使ってあらゆる操作を実行できる.

Amazon Resource Name (ARN)

AWS 上のあらゆるリソースには, Amazon Resource Name (ARN) という固有の ID が付与されている. ARN は arn:aws:s3:::my_bucket/ のようなフォーマットで記述され,ARN を使用することで,特定の AWS リソース (S3 のバケットや EC2 のインスタンス) を一意的に参照することができる.

S3 バケットや EC2 インスタンスなどには ARN に加えて,人間が読みやすい名前を定義することも可能である. この場合は,ARN または名前のどちらを用いても同じリソースを参照することが可能である.

CloudFormation と AWS CDK

CloudFormation による Infrastructure as Code (IaC)

前節で述べたように,AWS API を使うことでクラウドのあらゆるリソースの作成・管理が可能である. よって,原理上は, API のコマンドを組み合わせていくことで,自分の作りたいクラウドを設計することができる.

しかし,ここで実用上考慮しなければならない点が一つある. AWS API には大きく分けて,リソースを操作するコマンドと,タスクを実行するコマンドがあることである (figure_title).

AWS APIはリソースを操作するコマンドとタスクを実行するコマンドに大きく分けられる.リソースを記述・管理するのに使われるのが, CloudFormation と CDK である.

リソースを操作するとは,EC2 のインスタンスを起動したり,S3 のバケットを作成したり,データベースに新たなテーブルを追加する,などの静的なリソースを準備する 操作を指す. "ハコ"を作る操作とよんでも良いだろう. このようなコマンドは,クラウドのデプロイ時にのみ,一度だけ実行されればよい

タスクを実行するコマンド とは, EC2 のインスタンスにジョブを投入したり, S3 のバケットにデータを読み書きするなどの操作を指す. これは, EC2 や S3 などのリソース ("ハコ") を前提として,その内部で実行されるべき計算を記述するものである. 前者に比べてこちらは動的な操作を担当する,と捉えることもできる.

そのような観点から,インフラを記述するプログラムタスクを実行するプログラムはある程度分けて管理されるべきである. クラウドの開発は,クラウドの(静的な)リソースを記述するプログラムを作成するステップと,インフラ上で動く動的な操作を行うプログラムを作成するステップの二段階に分けて考えることができる.

AWS での静的リソースを管理するための仕組みが, CloudFormation である. CloudFormation とは, CloudFormation の文法に従ったテキストファイルを使って,AWS のインフラを記述する仕組みである. CloudFormation を使って,たとえば,EC2 のインスタンスをどれくらいのスペックで,何個起動するか,インスタンス間はどのようなネットワークで結び,どのようなアクセス権限を付与するか,などのリソースの要件を逐次的に記述することができる. 一度 CloudFormation ファイルができ上がれば,それにしたがったクラウドシステムをコマンド一つで AWS 上に展開することができる. また,CloudFormation ファイルを交換することで,全く同一のクラウド環境を他者が簡単に再現することも可能になる. このように,本来は物理的な実体のあるハードウェアを,プログラムによって記述し,管理するという考え方を,**Infrastructure as Code (IaC)**とよぶ.

CloudFormation を記述するには,基本的に JSON (JavaScript Object Notation) とよばれるフォーマットを使う. 次のコードは,JSON で記述された CloudFormation ファイルの一例 (抜粋) である.

json
"Resources" : {
  ...
  "WebServer": {
    "Type" : "AWS::EC2::Instance",
    "Properties": {
      "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" },
                        { "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" }, "Arch" ] } ] },
      "InstanceType"   : { "Ref" : "InstanceType" },
      "SecurityGroups" : [ {"Ref" : "WebServerSecurityGroup"} ],
      "KeyName"        : { "Ref" : "KeyName" },
      "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [
                     "#!/bin/bash -xe\n",
                     "yum update -y aws-cfn-bootstrap\n",

                     "/opt/aws/bin/cfn-init -v ",
                     "         --stack ", { "Ref" : "AWS::StackName" },
                     "         --resource WebServer ",
                     "         --configsets wordpress_install ",
                     "         --region ", { "Ref" : "AWS::Region" }, "\n",

                     "/opt/aws/bin/cfn-signal -e $? ",
                     "         --stack ", { "Ref" : "AWS::StackName" },
                     "         --resource WebServer ",
                     "         --region ", { "Ref" : "AWS::Region" }, "\n"
      ]]}}
    },
    ...
  },
  ...
},
"Resources" : {
  ...
  "WebServer": {
    "Type" : "AWS::EC2::Instance",
    "Properties": {
      "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" },
                        { "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" }, "Arch" ] } ] },
      "InstanceType"   : { "Ref" : "InstanceType" },
      "SecurityGroups" : [ {"Ref" : "WebServerSecurityGroup"} ],
      "KeyName"        : { "Ref" : "KeyName" },
      "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [
                     "#!/bin/bash -xe\n",
                     "yum update -y aws-cfn-bootstrap\n",

                     "/opt/aws/bin/cfn-init -v ",
                     "         --stack ", { "Ref" : "AWS::StackName" },
                     "         --resource WebServer ",
                     "         --configsets wordpress_install ",
                     "         --region ", { "Ref" : "AWS::Region" }, "\n",

                     "/opt/aws/bin/cfn-signal -e $? ",
                     "         --stack ", { "Ref" : "AWS::StackName" },
                     "         --resource WebServer ",
                     "         --region ", { "Ref" : "AWS::Region" }, "\n"
      ]]}}
    },
    ...
  },
  ...
},

ここでは, "WebServer" という名前のつけられた EC2 インスタンスを定義している.かなり長大で複雑な記述であるが,これによって所望のスペック・OS をもつ EC2 インスタンスを自動的に生成することが可能になる.

AWS CDK

前節で紹介した CloudFormation は,見てわかるとおり大変記述が複雑であり,またそれのどれか一つにでも誤りがあってはいけない. また,基本的に"テキスト"を書いていくことになるので,プログラミング言語で使うような変数やクラスといった便利な概念が使えない (厳密には, CloudFormation にも変数に相当するような機能は存在する). また,記述の多くの部分は繰り返しが多く,自動化できる部分も多い.

そのような悩みを解決してくれるのが, AWS Cloud Development Kit (CDK) である. CDK は Python などのプログラミング言語を使って CloudFormation を自動的に生成してくれるツールである. CDK は 2019 年にリリースされたばかりの比較的新しいツールで,日々改良が進められている (GitHub リポジトリ のリリースを見ればその開発のスピードの速さがわかるだろう). CDK は TypeScript (JavaScript), Python, Java など複数の言語でサポートされている.

CDK を使うことで,CloudFormation に相当するクラウドリソースの記述を,より親しみのあるプログラミング言語を使って行うことができる. かつ,典型的なリソース操作に関してはパラメータの多くの部分を自動で決定してくれるので,記述しなければならない量もかなり削減される.

以下に Python を使った CDK のコードの一例 (抜粋) を示す.

python
from aws_cdk import (
    core,
    aws_ec2 as ec2,
)

class MyFirstEc2(core.Stack):

    def __init__(self, scope, name, **kwargs):
        super().__init__(scope, name, **kwargs)

        vpc = ec2.Vpc(
            ... # some parameters
        )

        sg = ec2.SecurityGroup(
            ... # some parameters
        )

        host = ec2.Instance(
            self, "MyGreatEc2",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ec2.MachineImage.latest_amazon_linux(),
            vpc=vpc,
            ...
        )
from aws_cdk import (
    core,
    aws_ec2 as ec2,
)

class MyFirstEc2(core.Stack):

    def __init__(self, scope, name, **kwargs):
        super().__init__(scope, name, **kwargs)

        vpc = ec2.Vpc(
            ... # some parameters
        )

        sg = ec2.SecurityGroup(
            ... # some parameters
        )

        host = ec2.Instance(
            self, "MyGreatEc2",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ec2.MachineImage.latest_amazon_linux(),
            vpc=vpc,
            ...
        )

このコードは,一つ前に示した JSON を使った CloudFormation と実質的に同じことを記述している. とても煩雑だった CloudFormation ファイルに比べて, CDK と Python を使うことで格段に短く,わかりやすく記述できることができるのがわかるだろう.

本書の主題は,CDK を使って,コードを書きながら AWS の概念や開発方法を学んでいくことである. 後の章では CDK を使って様々なハンズオンを実施していく. 早速,最初のハンズオンでは, CDK を使って EC2 インスタンスを作成する方法を学んでいこう.

  • AWS CDK Examples: CDK を使ったプロジェクトの例が多数紹介されている. ここにある例をテンプレートに自分のアプリケーションの開発を進めるとよい.

Hands-on #1: 初めての EC2 インスタンスを起動する

ハンズオンの第一回では, CDK を使って EC2 のインスタンス(仮想サーバー)を作成し,SSH でサーバーにログインする,という演習を行う. このハンズオンを終えれば,あなたは自分だけのサーバーを AWS 上に立ち上げ,自由に計算を走らせることができるようになるのである!

準備

ハンズオンのソースコードは GitHub の handson/ec2-get-started に置いてある.

このハンズオンは,基本的に AWS の無料枠 の範囲内で実行することができる.

まずは,ハンズオンを実行するための環境を整える. これらの環境整備は,後のハンズオンでも前提となるものなので確実にミスなく行っていただきたい.

  • AWS Account: ハンズオンを実行するには個人の AWS アカウントが必要である. AWS アカウントの取得については AWS アカウントの取得 を参照のこと.
  • Python と Node.js: 本ハンズオンを実行するには,Python (3.6 以上),Node.js (12.0 以上) がインストールされていなければならない.
  • AWS CLI: AWS CLI のインストールについては, AWS CLI のインストール を参照. ここに記載されている認証鍵の設定も済ませておくこと.
  • AWS CDK: AWS CDK のインストールについては, AWS CDK のインストール を参照.
  • ソースコードのダウンロード: 本ハンズオンで使用するプログラムのソースコードを,以下のコマンドを使って GitHub からダウンロードする.
sh
$ git clone https://github.com/tomomano/learn-aws-by-coding.git
$ git clone https://github.com/tomomano/learn-aws-by-coding.git

あるいは, https://github.com/tomomano/learn-aws-by-coding のページに行って,右上のダウンロードボタンからダウンロードすることもできる.

Docker を使用する場合

Python, Node.js, AWS CDK など,ハンズオンのプログラムを実行するために必要なプログラム/ライブラリがインストール済みの Docker image を用意した. また,ハンズオンのソースコードもパッケージ済みである. Docker の使い方を知っている読者は,これを使えば,諸々のインストールをする必要なく,すぐにハンズオンのプログラムを実行できる.

使用方法については ハンズオン実行用の Docker image の使い方 を参照のこと.

SSH

SSH (secure shell) は Unix 系のリモートサーバーに安全にアクセスするためのツールである. 本ハンズオンでは, SSH を使って仮想サーバーにアクセスする. SSH に慣れていない読者のため,簡単な説明をここで行おう.

SSH による通信はすべて暗号化されているので,機密情報をインターネットを介して安全に送受信することができる. 本ハンズオンで,リモートのサーバーにアクセスするための SSH クライアントがローカルマシンにインストールされている必要がある. SSH クライアントは Linux/Mac には標準搭載されている. Windows の場合は WSL をインストールすることで SSH クライアントを利用することを推奨する (環境構築 を参照).

SSH コマンドの基本的な使い方を次に示す. <host name> はアクセスする先のサーバーの IP アドレスや DNS によるホストネームが入る. <user name> は接続する先のユーザー名である.

sh
$ ssh <user name>@<host name>
$ ssh <user name>@<host name>

SSH は平文のパスワードによる認証を行うこともできるが,より強固なセキュリティを施すため,公開鍵暗号方式(Public Key Cryptography)による認証を行うことが強く推奨されており, EC2 はこの方法でしかアクセスを許していない. 公開鍵暗号方式の仕組みについては各自勉強してほしい. 本ハンズオンにおいて大事なことは,EC2 インスタンスが公開鍵(Public key)を保持し,クライアントとなるコンピュータ(読者自身のコンピュータ)が秘密鍵(Private key)を保持する,という点である. EC2 のインスタンスには秘密鍵を持ったコンピュータのみがアクセスすることができる.逆に言うと,秘密鍵が漏洩すると第三者もサーバーにアクセスできることになるので,秘密鍵は絶対に漏洩することのないよう注意して管理する

SSH コマンドでは,ログインのために使用する秘密鍵ファイルを -i もしくは --identity_file のオプションで指定することができる. たとえば,次のように使う.

sh
$ ssh -i Ec2SecretKey.pem <user name>@<host name>
$ ssh -i Ec2SecretKey.pem <user name>@<host name>

アプリケーションの説明

このハンズオンで作成するアプリケーションの概要を figure_title に示す.

ハンズオン#1で作製するアプリケーションのアーキテクチャ

このアプリケーションではまず,VPC (Virtual Private Cloud) を使ってプライベートな仮想ネットワーク環境を立ち上げている. その VPC の public subnet の内側に,EC2 (Elatic Compute Cloud) の仮想サーバーを配置する. さらに,セキュリティのため, Security Group による EC2 インスタンスへのアクセス制限を設定している. このようにして作成された仮想サーバーに,SSH を使ってアクセスし,簡単な計算を行う.

figure_title のようなアプリケーションを,CDK を使って構築する.

早速ではあるが,今回のハンズオンで使用するプログラムを見てみよう (handson/ec2-get-started/app.py).

python
class MyFirstEc2(core.Stack):

    def __init__(self, scope: core.App, name: str, key_name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        vpc = ec2.Vpc(
            self, "MyFirstEc2-Vpc",
            max_azs=1,
            cidr="10.10.0.0/23",
            subnet_configuration=[
                ec2.SubnetConfiguration(
                    name="public",
                    subnet_type=ec2.SubnetType.PUBLIC,
                )
            ],
            nat_gateways=0,
        )

        #
        sg = ec2.SecurityGroup(
            self, "MyFirstEc2Vpc-Sg",
            vpc=vpc,
            allow_all_outbound=True,
        )
        sg.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(22),
        )

        #
        host = ec2.Instance(
            self, "MyFirstEc2Instance",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ec2.MachineImage.latest_amazon_linux(),
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            security_group=sg,
            key_name=key_name
        )
class MyFirstEc2(core.Stack):

    def __init__(self, scope: core.App, name: str, key_name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        vpc = ec2.Vpc(
            self, "MyFirstEc2-Vpc",
            max_azs=1,
            cidr="10.10.0.0/23",
            subnet_configuration=[
                ec2.SubnetConfiguration(
                    name="public",
                    subnet_type=ec2.SubnetType.PUBLIC,
                )
            ],
            nat_gateways=0,
        )

        #
        sg = ec2.SecurityGroup(
            self, "MyFirstEc2Vpc-Sg",
            vpc=vpc,
            allow_all_outbound=True,
        )
        sg.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(22),
        )

        #
        host = ec2.Instance(
            self, "MyFirstEc2Instance",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ec2.MachineImage.latest_amazon_linux(),
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            security_group=sg,
            key_name=key_name
        )
  • まず最初に,VPC を定義する.

  • 次に, security group (SG) を定義している. ここでは,任意の IPv4 のアドレスからの,ポート 22 (SSH の接続に使用される)への接続を許可している. それ以外の接続は拒絶される.

  • 最後に,上記で作った VPC と SG が付与された EC2 インスタンスを作成している. インスタンスタイプは t2.micro を選択し, Amazon Linux を OS として設定している.

それぞれについて,もう少し詳しく説明しよう.

VPC (Virtual Private Cloud)

VPC のアイコン.

VPC

VPC は AWS 上にプライベートな仮想ネットワーク環境を構築するツールである.高度な計算システムを構築するには,複数のサーバーを連動させて計算を行う必要があるが,そのような場合に互いのアドレスなどを管理する必要があり,そういった目的で VPC は有用である.

本ハンズオンでは,サーバーは一つしか起動しないので,VPC の恩恵はよく分からないかもしれない.しかし,EC2 インスタンスは必ず VPC の中に配置されなければならない,という制約があるので,このハンズオンでもミニマルな VPC を構成している.

興味のある読者のために,VPC のコードについてもう少し詳しく説明しよう.

python
vpc = ec2.Vpc(
    self, "MyFirstEc2-Vpc",
    max_azs=1,
    cidr="10.10.0.0/23",
    subnet_configuration=[
        ec2.SubnetConfiguration(
            name="public",
            subnet_type=ec2.SubnetType.PUBLIC,
        )
    ],
    nat_gateways=0,
)
vpc = ec2.Vpc(
    self, "MyFirstEc2-Vpc",
    max_azs=1,
    cidr="10.10.0.0/23",
    subnet_configuration=[
        ec2.SubnetConfiguration(
            name="public",
            subnet_type=ec2.SubnetType.PUBLIC,
        )
    ],
    nat_gateways=0,
)
  • max_azs=1 : このパラメータは,前章で説明した avaialibility zone (AZ) を設定している. このハンズオンでは,特にデータセンターの障害などを気にする必要はないので 1 にしている.

  • cidr="10.10.0.0/23" : このパラメータは,VPC 内の IPv4 のレンジを指定している. CIDR 記法については, Wikipediaなどを参照. 10.10.0.0/2310.10.0.0 から 10.10.1.255 までの 512 個の連続したアドレス範囲を指している. つまり,この VPC では最大で 512 個のユニークな IPv4 アドレスが使えることになる. 今回はサーバーは一つなので 512 個は明らかに多すぎるが,VPC はアドレスの数はどれだけ作成しても無料なので,多めに作成した.

  • subnet_configuration=... : このパラメータは,VPC にどのようなサブネットを作るか,を決めている. サブネットの種類には private subnetpublic subnet の二種類がある. private subnet は基本的にインターネットとは遮断されたサブネット環境である. インターネットと繋がっていないので,セキュリティは極めて高く, VPC 内のサーバーとのみ通信を行えばよい EC2 インスタンスはここに配置する. Public subnet とはインターネットに繋がったサブネットである. 本ハンズオンで作成するサーバーは,外から SSH でログインを行いたいので, Public subnet 内に配置する. より詳細な記述は 公式ドキュメンテーション を参照.

  • natgateways=0 : これは少し高度な内容なので省略する (興味のある読者は 公式ドキュメンテーションを参照). が,これを 0 にしておかないと,NAT Gateway の利用料金が発生してしまうので,注意!

Security Group

Security group (SG) は, EC2 インスタンスに付与することのできる仮想ファイアーウォールである. たとえば,特定の IP アドレスから来た接続を許可・拒絶したり (インバウンド・トラフィックの制限) ,逆に特定の IP アドレスへのアクセスを禁止したり (アウトバウンド・トラフィックの制限) することができる.

コードの該当部分を見てみよう.

python
sg = ec2.SecurityGroup(
    self, "MyFirstEc2Vpc-Sg",
    vpc=vpc,
    allow_all_outbound=True,
)
sg.add_ingress_rule(
    peer=ec2.Peer.any_ipv4(),
    connection=ec2.Port.tcp(22),
)
sg = ec2.SecurityGroup(
    self, "MyFirstEc2Vpc-Sg",
    vpc=vpc,
    allow_all_outbound=True,
)
sg.add_ingress_rule(
    peer=ec2.Peer.any_ipv4(),
    connection=ec2.Port.tcp(22),
)

本ハンズオンでは, SSH による外部からの接続を許容するため, sg.add_ingress_rule(peer=ec2.Peer.any_ipv4(), connection=ec2.Port.tcp(22)) により,すべての IPv4 アドレスからのポート 22 番へのアクセスを許容している. また, SSH で EC2 インスタンスにログインしたのち,インターネットからプログラムなどをダウンロードできるよう, allow_all_outbound=True のパラメータを設定している.

SSH はデフォルトでは 22 番ポートを使用するのが慣例である.

セキュリティ上の観点からは,SSH の接続は自宅や大学・職場など特定の地点からの接続のみを許す方が望ましい.

EC2 (Elastic Compute Cloud)

EC2 のアイコン.

EC2

EC2 は AWS 上に仮想サーバーを立ち上げるサービスである. 個々の起動状態にある仮想サーバーのことをインスタンス (instance) とよぶ (しかし,口語的なコミュニケーションにおいては,サーバーとインスタンスという言葉は相互互換的に用いられることが多い).

EC2 では用途に応じて様々なインスタンスタイプが提供されている. table_title に,代表的なインスタンスタイプの例を挙げる (執筆時点での情報). EC2 のインスタンスタイプのすべてのリストは 公式ドキュメンテーション "Amazon EC2 Instance Types" で見ることができる.

EC2 instance types
InstancevCPUMemory (GiB)Network bandwidth (Gbps)Price per hour ($)

t2.micro

1

1

-

0.0116

t2.small

1

2

-

0.023

t2.medium

2

4

-

0.0464

c5.24xlarge

96

192

25

4.08

c5n.18xlarge

72

192

100

3.888

x1e.16xlarge

64

1952

10

13.344

table_title からわかるように, CPU は 1 コアから 96 コアまで,メモリーは 1GB から 2TB 以上まで,ネットワーク帯域は最大で 100Gbps まで,幅広く選択することができる. また,時間あたりの料金は,CPU・メモリーの占有数にほぼ比例する形で増加する. EC2 はサーバーの起動時間を秒単位で記録しており,利用料金は使用時間に比例する形で決定される. 例えば, t2.medium のインスタンスを 10 時間起動した場合,0.0464 * 10 = 0.464 ドルの料金が発生する.

AWS には 無料利用枠 というものがあり, t2.micro であれば月に 750 時間までは無料で利用することができる.

table_title の価格は us-east-1 のものである. リージョンによって多少価格設定が異なる.

上記で t2.micro の $0.0116 / hour という金額は, On-demand インスタンスというタイプを選択した場合の価格である. EC2 ではほかに, Spot instance とよばれるインスタンスも存在しする. Spot instance は,AWS のデータセンターの負荷が増えた場合,ユーザーのプログラムが実行中であっても AWS の判断により強制シャットダウンされる,という不便さを抱えているのだが,その分大幅に安い料金設定になっている. AWS で一時的に生じた余剰な空き CPU をユーザーに割安で貸し出す,という発想である. 科学計算やウェブサーバーなどの用途でコストを削減する目的で, Spot Instance を活用する事例も多数報告されている.

EC2 インスタンスを定義しているコードの該当部分を見てみよう.

python
host = ec2.Instance(
    self, "MyFirstEc2Instance",
    instance_type=ec2.InstanceType("t2.micro"),
    machine_image=ec2.MachineImage.latest_amazon_linux(),
    vpc=vpc,
    vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
    security_group=sg,
    key_name=key_name
)
host = ec2.Instance(
    self, "MyFirstEc2Instance",
    instance_type=ec2.InstanceType("t2.micro"),
    machine_image=ec2.MachineImage.latest_amazon_linux(),
    vpc=vpc,
    vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
    security_group=sg,
    key_name=key_name
)

ここでは, t2.micro というインスタンスタイプを選択している. さらに, machine_image として, Amazon Linux を選択している (Machine image は OS と似た概念である. Machine image については, Hands-on #2: AWS でディープラーニングを実践 でより詳しく触れる). さらに,上で定義した VPC, SG をこのインスタンスに付与している.

以上が,今回使用するプログラムの簡単な解説であった. ミニマルな形のプログラムではあるが,仮想サーバーを作成するのに必要なステップがおわかりいただけただろうか?

プログラムを実行する

さて,ハンズオンのコードの理解ができたところで,プログラムを実際に実行してみよう.繰り返しになるが, 準備 での準備ができていることが前提である.

Python の依存ライブラリのインストール

まずは,Python の依存ライブラリをインストールする.以下では,Python のライブラリを管理するツールとして, venv を使用する.

まずは, handson/ec2-get-started のディレクトリに移動しよう.

sh
$ cd handson/ec2-get-started
$ cd handson/ec2-get-started

ディレクトリを移動したら, venv で新しい仮想環境を作成し,インストールを実行する.

sh
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

これで Python の環境構築は完了だ.

venv の簡単な説明は Python クイックガイド に記述してある.

環境によっては pip ではなく pip3 あるいは python3 -m pip に置き換える必要がある.

AWS のシークレットキーをセットする

AWS CLI および AWS CDK を使うには, AWS のシークレットキーが設定されている必要がある. シークレットキーの発行については AWS のシークレットキーの作成 を参照のこと. シークレットキーを発行したら, AWS CLI のインストール を参照し,コマンドラインの設定を行う.

手順をここに短く要約すると,一つ目の方法は AWS_ACCESS_KEY_ID などの環境変数を設定するやり方である. もう一つの方法は, ~/.aws/credentials に認証情報を保存しておく方式である. シークレットキーの設定は AWS CLI/CDK を使用するうえで共通のステップになるので,しっかりと理解しておくように.

SSH 鍵を生成

EC2 インスタンスには SSH を使ってログインする. EC2 インスタンスを作成するのに先行して,今回のハンズオンで専用に使う SSH の公開鍵・秘密鍵のペアを準備する必要がある.

次の AWS CLI コマンドにより, HirakeGoma という名前のついた鍵を生成する.

sh
$ export KEY_NAME="HirakeGoma"
$ aws ec2 create-key-pair --key-name ${KEY_NAME} --query 'KeyMaterial' --output text > ${KEY_NAME}.pem
$ export KEY_NAME="HirakeGoma"
$ aws ec2 create-key-pair --key-name ${KEY_NAME} --query 'KeyMaterial' --output text > ${KEY_NAME}.pem

このコマンドを実行すると,現在のディレクトリに HirakeGoma.pem というファイルが作成される.これが,サーバーにアクセスするための秘密鍵である. SSH でこの鍵を使うため, ~/.ssh/ のディレクトリに鍵を移動する. さらに,秘密鍵が書き換えられたり第三者に閲覧されないよう,ファイルのアクセス権限を 400 に設定する.

sh
$ mv HirakeGoma.pem ~/.ssh/
$ chmod 400 ~/.ssh/HirakeGoma.pem
$ mv HirakeGoma.pem ~/.ssh/
$ chmod 400 ~/.ssh/HirakeGoma.pem

デプロイを実行

これまでのステップで, EC2 インスタンスをデプロイするための準備が整った! 早速,次のコマンドによりアプリケーションを AWS にデプロイしよう. -c key_name="HirakeGoma" というオプションで,先ほど生成した HirakeGoma という名前の鍵を使うよう指定している.

sh
$ cdk deploy -c key_name="HirakeGoma"
$ cdk deploy -c key_name="HirakeGoma"

このコマンドを実行すると, VPC, EC2 などが AWS 上に展開される. そして,コマンドの出力の最後に figure_title のような出力が得られるはずである. 出力の中で InstancePublicIp に続く数字が,起動したインスタンスのパブリック IP アドレスである. IP アドレスはデプロイごとにランダムなアドレスが割り当てられる.

CDKデプロイ実行後の出力

SSH でログイン

早速,SSH  で接続してみよう.

sh
$ ssh -i ~/.ssh/HirakeGoma.pem ec2-user@<IP address>
$ ssh -i ~/.ssh/HirakeGoma.pem ec2-user@<IP address>

-i オプションで,先ほど生成した秘密鍵を指定している. EC2 インスタンスにはデフォルトで ec2-user という名前のユーザーが作られているので,それを使用する. 最後に, <IP address> の部分は自身が作成した EC2 インスタンスの IP アドレスで置き換える (12.345.678.9 など).

ログインに成功すると, figure_title のような画面が表示される. リモートのサーバーにログインしているので,プロンプトが [ec2-user@ip-10-10-1-217 ~]$ のようになっていることを確認しよう.

SSH で EC2 インスタンスにログイン

おめでとう!これで,めでたく AWS 上に EC2 仮想サーバーを起動し,リモートからアクセスできるようになった!

起動した EC2 インスタンスで遊んでみる

せっかく新しいインスタンスを起動したので,少し遊んでみよう.

ログインした EC2 インスタンスで,次のコマンドを実行してみよう. CPU の情報を取得することができる.

sh
$ cat /proc/cpuinfo

processor       : 0
vendor_id       : GenuineIntel
cpu family      : 6
model           : 63
model name      : Intel(R) Xeon(R) CPU E5-2676 v3 @ 2.40GHz
stepping        : 2
microcode       : 0x43
cpu MHz         : 2400.096
cache size      : 30720 KB
$ cat /proc/cpuinfo

processor       : 0
vendor_id       : GenuineIntel
cpu family      : 6
model           : 63
model name      : Intel(R) Xeon(R) CPU E5-2676 v3 @ 2.40GHz
stepping        : 2
microcode       : 0x43
cpu MHz         : 2400.096
cache size      : 30720 KB

次に,実行中のプロセスやメモリの消費を見てみよう.

sh
$  top -n 1

top - 09:29:19 up 43 min,  1 user,  load average: 0.00, 0.00, 0.00
Tasks:  76 total,   1 running,  51 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.3%us,  0.3%sy,  0.1%ni, 98.9%id,  0.2%wa,  0.0%hi,  0.0%si,  0.2%st
Mem:   1009140k total,   270760k used,   738380k free,    14340k buffers
Swap:        0k total,        0k used,        0k free,   185856k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
    1 root      20   0 19696 2596 2268 S  0.0  0.3   0:01.21 init
    2 root      20   0     0    0    0 S  0.0  0.0   0:00.00 kthreadd
    3 root      20   0     0    0    0 I  0.0  0.0   0:00.00 kworker/0:0
$  top -n 1

top - 09:29:19 up 43 min,  1 user,  load average: 0.00, 0.00, 0.00
Tasks:  76 total,   1 running,  51 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.3%us,  0.3%sy,  0.1%ni, 98.9%id,  0.2%wa,  0.0%hi,  0.0%si,  0.2%st
Mem:   1009140k total,   270760k used,   738380k free,    14340k buffers
Swap:        0k total,        0k used,        0k free,   185856k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
    1 root      20   0 19696 2596 2268 S  0.0  0.3   0:01.21 init
    2 root      20   0     0    0    0 S  0.0  0.0   0:00.00 kthreadd
    3 root      20   0     0    0    0 I  0.0  0.0   0:00.00 kworker/0:0

t2.micro インスタンスなので, 1009140k = 1GB のメモリーがあることがわかる.

今回起動したインスタンスには Python 2 はインストール済みだが, Python 3 は入っていない. Python 3.6 のインストールを行ってみよう. インストールは簡単である.

sh
$ sudo yum update -y
$ sudo yum install -y python36
$ sudo yum update -y
$ sudo yum install -y python36

インストールした Python を起動してみよう.

sh
$ python3
Python 3.6.10 (default, Feb 10 2020, 19:55:14)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
$ python3
Python 3.6.10 (default, Feb 10 2020, 19:55:14)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Python のインタープリタが起動した! Ctrl + D あるいは exit() と入力することで,インタープリタを閉じることができる.

さて,サーバーでのお遊びはこんなところにしておこう (興味があれば各自いろいろと試してみると良い) . 次のコマンドでログアウトする.

sh
$ exit
$ exit

AWS コンソールから確認

これまでは,すべてコマンドラインから EC2 に関連する操作を行ってきた. EC2 インスタンスの状態を確認したり,サーバーをシャットダウンするなどの操作は,AWS コンソールから実行することもできる. 軽くこれを紹介しよう.

まず,ウェブブラウザを開いて AWS コンソールにログインする. ログインしたら, Services から EC2 を検索(選択)する. 次に,左のサイドバーの Instances とページをたどる. すると, figure_title のような画面が得られるはずである. この画面で,自分のアカウントの管理下にあるインスタンスを確認できる. 同様に,VPC・SG についてもコンソールから確認できる.

EC2 コンソール画面

コンソール右上で,正しいリージョン (今回の場合は ap-northeast-1, Tokyo) が選択されているか,注意する!

前章で CloudFormation について触れたが,今回デプロイしたアプリケーションも,CloudFormation のスタックとして管理されている. スタック (stack) とは, AWS リソースの集合のことを指す. 今回の場合は, VPC/EC2/SG などがスタックの中に含まれている. コンソールで CloudFormation のページに行ってみよう (figure_title).

CloudFormation コンソール画面

"MyFirstEc2" という名前のスタックがあることが確認できる. クリックをして中身を見てみると,EC2, VPC などのリソースがこのスタックに紐付いていることがわかる.

スタックを削除

これにて,第一回のハンズオンで説明すべき事柄はすべて完了した. 最後に,使わなくなったスタックを削除しよう. スタックの削除には,二つの方法がある.

一つ目の方法は,前節の Cloudformation のコンソール画面で, "Delete" ボタンを押すことである (figure_title). すると,スタックの状態が "DELETE_IN_PROGRESS" に変わり,削除が完了すると CloudFormation のスタックの一覧から消える.

CloudFormationコンソール画面から,スタックを削除

二つ目の方法は,コマンドラインから行う方法である. 先ほど,デプロイを行ったコマンドラインに戻ろう. そうしたら,次のコマンドを実行する.

sh
$ cdk destroy
$ cdk destroy

このコマンドを実行すると,スタックの削除が始まる. 削除した後は,VPC, EC2 など,すべて跡形もなく消え去っていることを自身で確かめよう. CloudFormation を用いることで関連するすべての AWS リソースを一度に管理・削除することができるので,大変便利である.

スタックの削除は各自で必ず行うこと! 行わなかった場合, EC2 インスタンスの料金が発生し続けることになる!

また,本ハンズオンのために作成した SSH 鍵ペアも不要なので,削除しておく. まず, EC2 側に登録してある公開鍵を削除する. これも,コンソールおよびコマンドラインの二つの方法で実行できる.

コンソールから実行するには, EC2 の画面に行き,左のサイドバーの Key Pairs を選択する. 鍵の一覧が表示されるので, HirakeGoma とある鍵にチェックを入れ,画面右上の Actions から, Delete を実行する (figure_title).

EC2でSSH鍵ペアを削除

コマンドラインから実行するには,次のコマンドを使う.

sh
$ aws ec2 delete-key-pair --key-name "HirakeGoma"
$ aws ec2 delete-key-pair --key-name "HirakeGoma"

最後に,ローカルのコンピュータから鍵を削除する.

sh
$ rm -f ~/.ssh/HirakeGoma.pem
$ rm -f ~/.ssh/HirakeGoma.pem

これで,クラウドの片付けもすべて終了だ.

なお,頻繁に EC2 インスタンスを起動したりする場合は,いちいち SSH 鍵を削除する必要はない.

小括

ここまでが,本書の第一部の内容である. 盛りだくさんの内容であったが,ついてこれたであろうか?

クラウド概論 では,クラウドの定義と用語の説明を行ったあと,なぜクラウドを使うのか,という点を議論した. 続いて AWS 入門 では,クラウドを学ぶ具体的なプラットフォームとして AWS を取り上げ, AWS を使用するにあたり最低限必要な知識と用語の説明を行った. さらに, Hands-on #1: 初めての EC2 インスタンスを起動する のハンズオンでは AWS CLI と AWS CDK を使って,自身のプライベートなサーバーを AWS 上に立ち上げる演習を行った.

これらを通じて,いかに簡単に (たった数行のコマンドで!) 仮想サーバーを立ち上げたり,削除したりすることができるか,体験できただろう. 筆者は,クラウド概論 でクラウドの最も重要な側面はダイナミックに計算リソースを拡大・縮小できることである,と述べた. この言葉の意味が,ハンズオンを通じてより明らかになっただろうか? ここで学んだ技術を少し応用するだけで,自分のウェブページをホストする仮想サーバーを作成したり,大量のコアを搭載した EC2 インスタンスを用意して科学計算を実行するなど,いろいろなアプリケーションが実現できる.

次章からは,今回学んだクラウドの技術を基に,より現実に即した問題を解くことを体験してもらう. お楽しみに!

クラウドで行う科学計算・機械学習

計算機が発達した現代では,計算機によるシミュレーションやビッグデータの解析は,科学・エンジニアリングの研究の主要な柱である. これらの大規模な計算を実行するには,クラウドは最適である. 本章から始まる第二部では,どのようにしてクラウド上で科学計算を実行するのかを,ハンズオンとともに体験してもらう. 科学計算の具体的な題材として,今回は機械学習(深層学習)を取り上げる.

なお,本書では PyTorch ライブラリを使って深層学習のアルゴリズムを実装するが,深層学習および PyTorch の知識は不要である. 講義ではなぜ・どうやって深層学習をクラウドで実行するかに主眼を置いているので,実行するプログラムの詳細には立ち入らない. 将来,自分で深層学習を使う機会が来たときに,詳しく学んでもらいたい.

なぜ機械学習をクラウドで行うのか?

2010 年頃に始まった第三次 AI ブームのおかげで,学術研究だけでなく社会・ビジネスの文脈でも機械学習に高い関心が寄せられている. とくに,深層学習 (ディープラーニング) とよばれる多層のレイヤーからなるニューラルネットワークを用いたアルゴリズムは,画像認識や自然言語処理などの分野で圧倒的に高い性能を実現し,革命をもたらしている.

深層学習の特徴は,なんといってもそのパラメータの多さである. 層が深くなるほど,層間のニューロンを結ぶ重みパラメータの数が増大していく. たとえば,最新の言語モデルである GPT-3 には1750 億個ものパラメータが含まれている. このような膨大なパラメータを有することで,深層学習は高い表現力と汎化性能を実現しているのである.

GPT-3 に限らず,最近の SOTA (State-of-the-art) の性能を達成するニューラルネットワークでは,百万から億のオーダーのパラメータを内包することは頻繁になってきている. そのような巨大なニューラルネットを訓練 (最適化) させるのは,当然のことながら膨大な計算コストがかかる. 結果として,ひとつの計算機では丸一日以上の時間がかかる場合も珍しくない. 深層学習の発展の速度は目覚ましく,研究・ビジネス両方の観点からも,いかにスループットよくニューラルネットワークの最適化を行えるかが鍵となってくる. そのような問題を解決するのにとても有効な手段が,クラウドである! Hands-on #1: 初めての EC2 インスタンスを起動する でその片鱗を見たように,クラウドを使用することでゼロから数千に至るまでの数のインスタンスを動的に起動し,並列に計算を実行することができる. さらに,深層学習を加速させる目的で,深層学習の演算に専用設計された計算チップ (GPU など) がある. クラウドを利用すると,そのような専用計算チップも無尽蔵に利用することができる. 事実,先述した GPT-3 の学習も,詳細は明かされていないが,Microsoft 社のクラウドを使って行われたと報告されている.

GPU による深層学習の高速化

深層学習の計算で欠かすことのできない技術として, GPU (Graphics Processing Unit) について少し説明する.

GPU は,その名のとおり,元々はコンピュータグラフィックスを出力するための専用計算チップである. CPU (Central Processing Unit) に対し,グラフィックスの演算に特化した設計がなされている. 身近なところでは, XBox や PS5 などのゲームコンソールなどに搭載されているし,ハイエンドなノート型・デスクトップ型計算機にも搭載されていることがある. コンピュータグラフィックスでは,スクリーンにアレイ状に並んだ数百万個の画素をビデオレート (30 fps) 以上で処理する必要がある. そのため,GPU はコアあたりの演算能力は比較的小さいかわりに,チップあたり数百から数千のコアを搭載しており (figure_title),スクリーンの画素を並列的に処理することで,リアルタイムでの描画を実現している.

GPUのアーキテクチャ.GPUには数百から数千の独立した計算コアが搭載されている. (画像出典: https://devblogs.nvidia.com/nvidia-turing-architecture-in-depth/)

このように,コンピュータグラフィクスの目的で生まれた GPU だが,2010 年前後から,その高い並列計算能力をグラフィックス以外の計算 (科学計算など) に用いるという流れ (General-purpose computing on GPU; GPGPU) が生まれた. GPU のコアは,その設計から,行列の計算など,単純かつ規則的な演算が得意であり,そのような演算に対しては数個程度のコアしかもたない CPU に比べて圧倒的に高い計算速度を実現することができる. 現在では GPGPU は分子動力学や気象シミュレーション,そして機械学習など多くの分野で使われている.

ディープラーニングで最も頻繁に起こる演算が,ニューロンの出力を次の層のニューロンに伝える畳み込み (Convolution) 演算である (figure_title). 畳み込み演算は,まさに GPU が得意とする演算であり, CPU ではなく GPU を用いることで学習を飛躍的に (最大で数百倍程度) 加速させることができる.

ニューラルネットワークにおける畳み込み演算.

このように GPU は機械学習の計算で欠かせないものであるが,なかなか高価である. たとえば,科学計算・機械学習に専用設計された NVIDIA 社の Tesla V100 というチップは,一台で約百万円の価格が設定されている. 機械学習を始めるのに,いきなり百万円の投資はなかなか大きい. だが,クラウドを使えば,初期コスト0で GPU を使用することができる.

機械学習を行うのに, V100 が必ずしも必要というわけではない. むしろ,研究者などでしばしば行われるのは,コンピュータゲームに使われるグラフィックス用の GPU を買ってきて (NVIDIA GeForce シリーズなど),開発のときはをそれを用いる,というアプローチである. グラフィックス用のいわゆる"コンシューマ GPU"は,市場の需要が大きいおかげで,10 万円前後の価格で購入することができる. V100 と比べると,コンシューマ GPU はコアの数が少なかったり,メモリーが小さかったりなどで劣る点があるが, それらを除いては計算能力にとくに制限があるわけではなく,開発の段階では十分な性能である場合がほとんどである. プログラムができあがって,ビッグデータの解析や,モデルをさらに大きくしたいときなどに,クラウドは有効だろう.

クラウドで GPU を使うには, GPU が搭載された EC2 インスタンスタイプ (P3, P2, G3, G4 など) を選択しなければならない. table_title に,代表的な GPU 搭載のインスタンスタイプを挙げる (執筆時点での情報).

GPUを搭載したEC2インスタンスタイプ
InstanceGPUsGPU modelGPU Mem (GiB)vCPUMem (GiB)Price per hour ($)

p3.2xlarge

1

NVIDIA V100

16

8

61

3.06

p3n.16xlarge

8

NVIDIA V100

128

64

488

24.48

p2.xlarge

1

NVIDIA K80

12

4

61

0.9

g4dn.xlarge

1

NVIDIA T4

16

4

16

0.526

table_title からわかるとおり, CPU のみのインスタンスと比べると少し高い価格設定になっている. また,古い世代の GPU (V100 に対しての K80) はより安価な価格で提供されている. 1 インスタンスあたりの GPU の搭載数は 1 台から最大で 8 台まで選択することが可能である.

GPU を搭載した一番安いインスタンスタイプは, g4dn.xlarge であり,これには廉価かつ省エネルギー設計の NVIDIA T4 が搭載されている. 後のハンズオンでは,このインスタンスを使用して,ディープラーニングの計算を行ってみる.

table_title の価格は us-east-1 のものである. リージョンによって多少価格設定が異なる.

V100 を一台搭載した p3.2xlarge の利用料金は一時間あたり $3.06 である. V100 が約百万円で売られていることを考えると,約 3000 時間 (= 124 日間),通算で計算を行った場合に,クラウドを使うよりも V100 を自分で買ったほうがお得になる,という計算になる (実際には,自前で V100 を用意する場合は, V100 だけでなく, CPU やネットワーク機器,電気使用料も必要なので,百万円よりもさらにコストがかかる).

GPT-3 で使われた計算リソースの詳細は論文でも明かされていないのだが, Lambda 社のブログで興味深い考察が行われている (Lambda 社は機械学習に特化したクラウドサービスを提供している).

記事によると,1750 億のパラメータを訓練するには,一台の GPU (NVIDIA V100) を用いた場合,342 年の月日と 460 万ドルのクラウド利用料が必要となる,とのことである. GPT-3 のチームは,複数の GPU に処理を分散することで現実的な時間のうちに訓練を完了させたのであろうが,このレベルのモデルになってくるとクラウド技術の限界を攻めないと達成できないことは確かである.

深層学習を詳しく勉強したい人には以下の参考書を推薦したい. 深層学習の基礎的な概念や理論は普遍的であるが,この分野は日進月歩なので,常に最新の情報を取り入れることを忘れずに.

Hands-on #2: AWS でディープラーニングを実践

準備

ハンズオン第二回では, GPU を搭載した EC2 インスタンスを起動し,深層学習モデルの学習と推論を実行する演習を行う.

ハンズオンのソースコードは GitHub の handson/mnist に置いてある.

本ハンズオンの実行には,第一回ハンズオンで説明した準備 (準備) が整っていることを前提とする. それ以外に必要な準備はない.

初期状態の AWS アカウントでは, GPU 搭載の G タイプのインスタンスの起動上限が 0 になっていることがある. これを確認するには, AWS コンソールから EC2 の画面を開き,左のメニューから Limits を選択する. その中の Running On-Demand All G instances という数字が G インスタンスの起動上限を表している.

もし,これが 0 になっていた場合は, AWS の自動申請フォームから上限緩和のリクエストを送る必要がある. 詳しくは 公式ドキュメンテーション "Amazon EC2 service quotas" を参照のこと.

このハンズオンは, g4dn.xlarge タイプの EC2 インスタンスを使うので,東京 (ap-northeast-1) リージョンでは 0.71 $/hour のコストが発生する.

AWS Educate Starter Account を使用している読者へ: 執筆時点においては, Starter Account には GPU 搭載型インスタンスを起動できないという制限が設けられている. したがって, Starter Account のユーザーはこのハンズオンを実行することはできない. 興味のある読者は,制限のない一般アカウントを自分自身で取得する必要があることに注意.

アプリケーションの説明

このハンズオンで作成するアプリケーションの概要を figure_title に示す.

ハンズオン#2で作製するアプリケーションのアーキテクチャ

図の多くの部分が,第一回ハンズオンで作成したアプリケーションと共通していることに気がつくだろう. 少しの変更で,簡単にディープラーニングを走らせる環境を構築することができるのである!主な変更点は次の3点である.

  • GPU を搭載した g4dn.xlarge インスタンスタイプを使用

  • ディープラーニングに使うプログラムがあらかじめインストールされた DLAMI (後述) を使用

  • SSH にポートフォワーディングのオプションつけてサーバーに接続し,サーバーで起動している Jupyter Notebook (後述) を使ってプログラムを書いたり実行したりする

ハンズオンで使用するプログラムのコードをみてみよう handson/mnist/app.py). コードは第一回目とほとんど共通である.変更点のみ解説を行う.

python
class Ec2ForDl(core.Stack):

    def __init__(self, scope: core.App, name: str, key_name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        vpc = ec2.Vpc(
            self, "Ec2ForDl-Vpc",
            max_azs=1,
            cidr="10.10.0.0/23",
            subnet_configuration=[
                ec2.SubnetConfiguration(
                    name="public",
                    subnet_type=ec2.SubnetType.PUBLIC,
                )
            ],
            nat_gateways=0,
        )

        sg = ec2.SecurityGroup(
            self, "Ec2ForDl-Sg",
            vpc=vpc,
            allow_all_outbound=True,
        )
        sg.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(22),
        )

        host = ec2.Instance(
            self, "Ec2ForDl-Instance",
            instance_type=ec2.InstanceType("g4dn.xlarge"), #
            machine_image=ec2.MachineImage.generic_linux({
                "us-east-1": "ami-060f07284bb6f9faf",
                "ap-northeast-1": "ami-09c0c16fc46a29ed9"
            }), #
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            security_group=sg,
            key_name=key_name
        )
class Ec2ForDl(core.Stack):

    def __init__(self, scope: core.App, name: str, key_name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        vpc = ec2.Vpc(
            self, "Ec2ForDl-Vpc",
            max_azs=1,
            cidr="10.10.0.0/23",
            subnet_configuration=[
                ec2.SubnetConfiguration(
                    name="public",
                    subnet_type=ec2.SubnetType.PUBLIC,
                )
            ],
            nat_gateways=0,
        )

        sg = ec2.SecurityGroup(
            self, "Ec2ForDl-Sg",
            vpc=vpc,
            allow_all_outbound=True,
        )
        sg.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(22),
        )

        host = ec2.Instance(
            self, "Ec2ForDl-Instance",
            instance_type=ec2.InstanceType("g4dn.xlarge"), #
            machine_image=ec2.MachineImage.generic_linux({
                "us-east-1": "ami-060f07284bb6f9faf",
                "ap-northeast-1": "ami-09c0c16fc46a29ed9"
            }), #
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            security_group=sg,
            key_name=key_name
        )
  • ここで, g4dn.xlarge インスタンスタイプを選択している (第一回では, CPU のみの t2.micro だった). g4dn.xlarge のインスタンスタイプは, クラウドで行う科学計算・機械学習 ですでに触れた通り, NVIDIA T4 と呼ばれる廉価版モデルの GPU を搭載したインスタンスである. CPU は 4 core, メインメモリーは 16GB が割り当てあられている.

  • ここでは,Deep Learning 用の諸々のソフトウェアがプリンストールされた AMI (Deep Learning Amazon Machine Image; DLAMI) を選択している (第一回では,Amazon Linux という AMI を使用していた). 使用する AMI の ID は リージョンごとに指定する必要があり,ここでは us-east-1ap-northeast-1 でそれぞれ定義している.

DLAMI という新しい概念が出てきたので,説明しよう.

AMI が us-east-1ap-northeast-1 でしか定義されていないので,提供されているコードはこの二つのリージョンのみでデプロイ可能である. もしほかのリージョンを利用したい場合は, AMI の ID を自身で検索し,コードに書き込む必要がある.

DLAMI (Deep Learning Amazon Machine Image)

AMI (Amazon Machine Image) とは,大まかには OS (Operating System) に相当する概念である. 当然のことながら, OS がなければコンピュータはなにもできないので,EC2 インスタンスを起動するときには必ずなにかの OS を"インストール"する必要がある. EC2 が起動したときにロードされる OS に相当するものが, AMI である. AMI には,たとえば Ubuntu などの Linux 系 OS に加えて,Windows Server を選択することもできる. また, EC2 での使用に最適化された Amazon Linux という AMI も提供されている.

しかしながら, AMI を単なる OS と理解するのは過剰な単純化である. AMI には,ベースとなる (空っぽの) OS を選択することもできるが,それに加えて,各種のプログラムがインストール済みの AMI も定義することができる. 必要なプログラムがインストールされている AMI を見つけることができれば,自身でインストールを行ったり環境設定したりする手間が大幅に省ける. 具体例を挙げると,ハンズオン第一回では EC2 インスタンスに Python 3.6 をインストールする例を示したが,そのような操作をインスタンスが起動するたびに行うのは手間である!

AMI は, AWS 公式のものに加えて,サードパーティから提供されているものもある. また,自分自身の AMI を作って登録することも可能である (参考). AMI は EC2 のコンソールから検索することが可能である. あるいは,AWS CLI を使って,次のコマンドでリストを取得することができる (参考).

sh
$ aws ec2 describe-images --owners amazon
$ aws ec2 describe-images --owners amazon

ディープラーニングで頻繁に使われるプログラムがあらかじめインストールしてある AMI が, DLAMI (Deep Learning AMI) である. DLAMI には TensorFlow, PyTorch などの人気の高いディープラーニングのフレームワーク・ライブラリがすでにインストールされているため, EC2 インスタンスを起動してすぐさまディープラーニングの計算を実行できる.

本ハンズオンでは, Amazon Linux 2 をベースにした DLAMI を使用する (AMI ID = ami-09c0c16fc46a29ed9.この AMI は ap-northeast-1 でしか使用できない点に注意). AWS CLI を使って,この AMI の詳細情報を取得してみよう.

sh
$ aws ec2 describe-images --owners amazon --image-ids "ami-09c0c16fc46a29ed9" --region ap-northeast-1
$ aws ec2 describe-images --owners amazon --image-ids "ami-09c0c16fc46a29ed9" --region ap-northeast-1

AMI ID = ami-09c0c16fc46a29ed9 の詳細情報

figure_title のような出力が得られるはずである.得られた出力から,この DLAMI には PyTorch のバージョン 1.4.0 と 1.5.0 がインストールされていることがわかる. この DLAMI を使って,早速ディープラーニングの計算を実行してみよう.

DLAMI には具体的には何がインストールされているのだろうか? 興味のある読者のために,簡単な解説をしよう (参考: 公式ドキュメンテーション "What Is the AWS Deep Learning AMI?").

最も low-level なレイヤーとしては, GPU ドライバー がインストールされている. GPU ドライバーなしには OS は GPU とコマンドのやり取りをすることができない. 次のレイヤーが CUDAcuDNN である. CUDA は, NVIDIA 社が開発した, GPU 上で汎用コンピューティングを行うための言語であり, C++ 言語を拡張したシンタックスを備える. cuDNN は CUDA で書かれたディープラーニングのライブラリであり,n 次元の畳み込みなどの演算が実装されている. ここまでが, "Base" とよばれるタイプの DLAMI の中身である.

これに加えて, "Conda" とよばれるタイプには, "Base" のプログラム基盤の上に, TensorFlowPyTorch などのライブラリがインストールされている. さらに, Anaconda による仮想環境を使うことによって, TensorFlow の環境・ PyTorch の環境・ MxNet の環境など,フレームワークを簡単に切り替えることができる (これについては,後のハンズオンで触れる). また, Jupyter Notebook もインストール済みである.

スタックのデプロイ

スタックの中身が理解できたところで,早速スタックをデプロイしてみよう.

デプロイの手順は,ハンズオン 1 とほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). それぞれのコマンドの意味を忘れてしまった場合は,ハンズオン 1 に戻って復習していただきたい. シークレットキーの設定も忘れずに (AWS CLI のインストール).

sh
# プロジェクトのディレクトリに移動
$ cd handson/mnist

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# SSH鍵を生成
$ export KEY_NAME="HirakeGoma"
$ aws ec2 create-key-pair --key-name ${KEY_NAME} --query 'KeyMaterial' --output text > ${KEY_NAME}.pem
$ mv HirakeGoma.pem ~/.ssh/
$ chmod 400 ~/.ssh/HirakeGoma.pem

# デプロイを実行
$ cdk deploy -c key_name="HirakeGoma"
# プロジェクトのディレクトリに移動
$ cd handson/mnist

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# SSH鍵を生成
$ export KEY_NAME="HirakeGoma"
$ aws ec2 create-key-pair --key-name ${KEY_NAME} --query 'KeyMaterial' --output text > ${KEY_NAME}.pem
$ mv HirakeGoma.pem ~/.ssh/
$ chmod 400 ~/.ssh/HirakeGoma.pem

# デプロイを実行
$ cdk deploy -c key_name="HirakeGoma"

ハンズオン 1 で作成した SSH 鍵の削除を行わなかった場合は, SSH 鍵を改めて作成する必要はない. 逆に言うと,同じ名前の SSH がすでに存在する場合は,鍵生成のコマンドはエラーを出力する.

デプロイのコマンドが無事に実行されれば, figure_title のような出力が得られるはずである.AWS により割り振られた IP アドレス (InstancePublicIp に続く文字列) をメモしておこう.

CDKデプロイ実行後の出力

ログイン

早速,デプロイしたインスタンスに SSH でログインしてみよう. ここでは,この後で使う Jupyter Notebook に接続するため,ポートフォワーディング (port forwarding) のオプション (-L) をつけてログインする.

sh
$ ssh -i ~/.ssh/HirakeGoma.pem -L localhost:8931:localhost:8888 ec2-user@<IP address>
$ ssh -i ~/.ssh/HirakeGoma.pem -L localhost:8931:localhost:8888 ec2-user@<IP address>

ポートフォワーディングとは,クライアントマシンの特定のアドレスへの接続を, SSH の暗号化された通信を介して,リモートマシンの特定のアドレスへ転送する,という意味である. このコマンドの -L localhost:8931:localhost:8888 は,自分のローカルマシンの localhost:8931 へのアクセスを,リモートサーバーの localhost:8888 のアドレスに転送せよ,という意味である (: につづく数字は TCP/IP ポートの番号を意味している). リモートサーバーのポート 8888 には,後述する Jupyter Notebook が起動している. したがって,ローカルマシンの localhost:8931 にアクセスすることで,リモートサーバーの Jupyter Notebook にアクセスすることができるのである (figure_title). このような SSH による接続方式をトンネル接続とよぶ.

SSH のポートフォワーディングによる Jupyter Notebook へのアクセス

ポートフォワーディングのオプションで,ポートの番号 (:8931, :8888 など) には 1 から 65535 までの任意の整数を指定できる. しかし,たとえば ポート 22 (SSH) やポート 80 (HTTP) など,いくつかすでに使われているポート番号もあることに注意する. また, Jupyter Notebook はデフォルトではポート 8888 番を使用する. したがって,リモート側のポート番号は,8888 を使うのがよい.

SSH ログインコマンドの <IP address> 部分は自身のインスタンスの IP アドレスを代入することを忘れずに.

本書の提供している Docker を使ってデプロイを実行した人へ

SSH によるログインは, Docker の外 (すなわちクライアントマシン本体) から行わなければならない. なぜなら,Jupyter を開くウェブブラウザは Docker の外にあるからである.

その際,秘密鍵を Docker の外にもってこなければならない. 手っ取り早い方法は, cat ~/.ssh/HirakeGoma と打って,出力結果をコピーしてホストマシンのファイルに書き込む方法である. あるいは -v オプションをつけて,ファイルシステムをマウントしてもよい (詳しくは Docker 公式ドキュメンテーション "Use volumes" を参照).

SSH によるログインができたら,早速, GPU の状態を確認してみよう. 次のコマンドを実行する.

sh
$ nvidia-smi
$ nvidia-smi

figure_title のような出力が得られるはずである. 出力を見ると, Tesla T4 型の GPU が 1 台搭載されていることが確認できる. その他,GPU Driver や CUDA のバージョン, GPU の負荷・メモリー使用率などの情報を確認することができる.

nvidia-smi の出力

Jupyter Notebook の起動

Jupyter Notebook とは,インタラクティブに Python のプログラムを書いたり実行したりするためのツールである. Jupyter は GUI としてウェブブラウザを介してアクセスする形式をとっており,まるでノートを書くように,プロットやテーブルのデータも美しく表示することができる (figure_title). Python に慣れている読者は,きっと一度は使ったことがあるだろう.

Jupyter Notebook の画面

このハンズオンでは, Jupyter Notebook を使ってディープラーニングのプログラムをインタラクティブに実行していく. DLAMI には既に Jupyter がインストールされているので,特段の設定なしに使い始めることができる.

早速, Jupyter を起動しよう. SSH でログインした先の EC2 インスタンスで,次のコマンドを実行すればよい.

sh
$ cd ~ # go to home directory
$ jupyter notebook
$ cd ~ # go to home directory
$ jupyter notebook

このコマンドを実行すると, figure_title のような出力が確認できるだろう. この出力から,Jupyter のサーバーが EC2 インスタンスの localhost:8888 というアドレスに起動していることがわかる. また, localhost:8888 に続く ?token=XXXX は,アクセスに使うための一時的なトークンである.

Jupyter Notebook サーバーを起動

Jupyter Notebook を初回に起動するときは,起動に数分程度の時間がかかることがある. ほかの動作も起動直後は遅く,いくつかプログラムを走らせていくうちに俊敏に反応するようになってくる. これは, AWS の GPU 搭載型仮想マシンの運用方法に起因する現象だと考えられる.

先ほど,ポートフォワーディングのオプションをつけて SSH 接続をしているので, Jupyter の起動している localhost:8888 には,ローカルマシンの localhost:8931 からアクセスすることができる. したがって,ローカルマシンから Jupyter にアクセスするには,ウェブブラウザ (Chrome, FireFox など)から次のアドレスにアクセスすれば良い.

http://localhost:8931/?token=XXXX&lt;/programlisting&gt;

?token=XXXX の部分は,上で Jupyter を起動したときに発行されたトークンの値に置き換える.

上のアドレスにアクセスすると, Jupyter のホーム画面が起動するはずである (figure_title). これで, Jupyter の準備が整った!

Jupyter ホーム画面

Jupyter Notebook の使い方 (超簡易版)

  • Shift + Enter: セルを実行

  • Esc: Command mode に遷移

  • メニューバーの "+" ボタン または Command mode で A ⇒ セルを追加

  • メニューバーの "ハサミ" ボタン または Command mode で X ⇒ セルを削除

ショートカットの一覧などは Ventsislav Yordanov 氏によるブログ が参考になる.

PyTorch はじめの一歩

PyTorch は Facebook AI Research LAB (FAIR) が中心となって開発を進めている,オープンソースのディープラーニングのライブラリである. PyTorch は 有名な例で言えば Tesla 社の自動運転プロジェクトなどで使用されており,執筆時点において最も人気の高いディープラーニングライブラリの一つである. 本ハンズオンでは, PyTorch を使ってディープラーニングの実践を行う.

PyTorch の歴史のお話

Facebook は PyTorch のほかに Caffe2 とよばれるディープラーニングのフレームワークを開発していた (初代 Caffe は UC Berkley の博士課程学生だった Yangqing Jia によって創られた). Caffe2 は 2018 年に PyTorch プロジェクトに合併された.

また,2019 年 12 月,日本の Preferred Networks 社が開発していた Chainer も開発を終了し,PyTorch の開発チームと協業していくことが発表された (詳しくは プレスリリース を参照). PyTorch には,開発統合前から Chainer からインスパイアされた API がいくつもあり, Chainer の DNA は今も PyTorch に引き継がれているのである…!

本格的なディープラーニングの計算に移る前に, PyTorch ライブラリを使って, GPU で計算を行うとはどういうものか,その入り口に触れてみよう.

まずは,新しいノートブックを作成する. Jupyter のホーム画面の右上の "New" を押し,"conda_pytorch_p36" という環境を選択したうえで,新規ノートブックを作成する (figure_title). "conda_pytorch_p36" の仮想環境には, PyTorch がインストール済みである.

新規ノートブックの作成. "conda_pytorch_p36" の環境を選択する.

ここでは,次のようなプログラムを書いて,実行していく. (figure_title).

PyTorch始めの一歩

まずは, PyTorch をインポートする.さらに, GPU が使える環境にあるか,確認する.

python
import torch
print("Is CUDA ready?", torch.cuda.is_available())
import torch
print("Is CUDA ready?", torch.cuda.is_available())

出力:

Is CUDA ready? True</programlisting>

次に,3x3 のランダムな行列を CPU 上に作ってみよう.

python
x = torch.rand(3,3)
print(x)
x = torch.rand(3,3)
print(x)

出力:

tensor([[0.6896, 0.2428, 0.3269], [0.0533, 0.3594, 0.9499], [0.9764, 0.5881, 0.0203]])</programlisting>

次に,行列を GPU 上に作成する.

python
y = torch.ones_like(x, device="cuda")
x = x.to("cuda")
y = torch.ones_like(x, device="cuda")
x = x.to("cuda")

そして,行列 xy の加算を,GPU 上で実行する

python
z = x + y
print(z)
z = x + y
print(z)

出力:

tensor([[1.6896, 1.2428, 1.3269], [1.0533, 1.3594, 1.9499], [1.9764, 1.5881, 1.0203]], device='cuda:0')</programlisting>

最後に, GPU 上にある行列を, CPU に戻す.

python
z = z.to("cpu")
print(z)
z = z.to("cpu")
print(z)

出力:

tensor([[1.6896, 1.2428, 1.3269], [1.0533, 1.3594, 1.9499], [1.9764, 1.5881, 1.0203]])</programlisting>

以上の例は, GPU を使った計算の初歩の初歩であるが,雰囲気はつかめただろうか? CPU と GPU で明示的にデータを交換するのが肝である. この例はたった 3x3 の行列の足し算なので, GPU を使う意味はまったくないが,これが数千,数万のサイズの行列になったとき, GPU は格段の威力を発揮する.

完成した Jupyter Notebook は /handson/mnist/pytorch/pytorch_get_started.ipynb にある. Jupyter の画面右上の "Upload" からこのファイルをアップロードして,コードを走らせることが可能である.

しなしながら,勉強のときにはコードはすべて自分の手で打つことが,記憶に残りやすくより効果的である,というのが筆者の意見である.

実際にベンチマークを取ることで GPU と CPU の速度を比較をしてみよう. 実行時間を計測するツールとして, Jupyter の提供する %time マジックコマンドを利用する.

まずは CPU を使用して,10000x10000 の行列の行列積を計算した場合の速度を測ってみよう. 先ほどのノートブックの続きに,次のコードを実行する.

python
s = 10000
device = "cpu"
x = torch.rand(s, s, device=device, dtype=torch.float32)
y = torch.rand(s, s, device=device, dtype=torch.float32)

%time z = torch.matmul(x,y)
s = 10000
device = "cpu"
x = torch.rand(s, s, device=device, dtype=torch.float32)
y = torch.rand(s, s, device=device, dtype=torch.float32)

%time z = torch.matmul(x,y)

出力は以下のようなものが得られるだろう. これは,行列積の計算に実時間で 5.8 秒かかったことを意味する (実行のたびに計測される時間はばらつくことに留意).

CPU times: user 11.5 s, sys: 140 ms, total: 11.6 s Wall time: 5.8 s</programlisting>

次に, GPU を使用して,同じ演算を行った場合の速度を計測しよう.

python
s = 10000
device = "cuda"
x = torch.rand(s, s, device=device, dtype=torch.float32)
y = torch.rand(s, s, device=device, dtype=torch.float32)
torch.cuda.synchronize()

%time z = torch.matmul(x,y); torch.cuda.synchronize()
s = 10000
device = "cuda"
x = torch.rand(s, s, device=device, dtype=torch.float32)
y = torch.rand(s, s, device=device, dtype=torch.float32)
torch.cuda.synchronize()

%time z = torch.matmul(x,y); torch.cuda.synchronize()

出力は以下のようなものになるだろう. GPU では 553 ミリ秒 で計算を終えることができた!

CPU times: user 334 ms, sys: 220 ms, total: 554 ms Wall time: 553 ms</programlisting>

PyTorch において, GPU での演算は asynchronous (非同期) で実行される. その理由で,上のベンチマークコードでは, torch.cuda.synchronize() というステートメントを埋め込んである.

このベンチマークでは, dtype=torch.float32 と指定することで,32bit の浮動小数点型を用いている. ディープラーニングの学習および推論の計算には,32bit 型,場合によっては 16bit 型が使われるのが一般的である. これの主な理由として,教師データやミニバッチに起因するノイズが,浮動小数点の精度よりも大きいことがあげられる. 32bit/16bit を採用することで,メモリー消費を抑えたり,計算速度の向上が達成できる.

上記のベンチマークから,GPU を用いることで,約 10 倍のスピードアップを実現することができた. スピードアップの性能は,演算の種類や行列のサイズに依存する. 行列積は,そのなかでも最も速度向上が見込まれる演算の一つである.

実践ディープラーニング! MNIST 手書き数字認識タスク

ここまで,AWS 上でディープラーニングの計算をするための概念や前提知識をながながと説明してきたが,ついにここからディープラーニングの計算を実際に走らせてみる.

ここでは,機械学習のタスクで最も初歩的かつ有名な MNIST データセットを使った数字認識を扱う (figure_title). これは,0 から 9 までの手書きの数字の画像が与えられ,その数字が何の数字なのかを当てる,というシンプルなタスクである.

MNIST 手書き数字データセット

今回は, MNIST 文字認識タスクを,畳み込みニューラルネットワーク (Convolutional Neural Network; CNN) を使って解く. ソースコードは /handson/minist/pytorch/ にある mnist.ipynbsimple_mnist.py である. なお,このプログラムは, PyTorch の公式 Example Project 集 を参考に,多少の改変を行ったものである.

まずは,カスタムのクラスや関数が定義された simple_mnist.py をアップロードしよう (figure_title). 画面右上の "Upload" ボタンをクリックし,ファイルを選択することでアップロードができる. この Python プログラムの中に,CNN のモデルや,学習の各イテレーションにおけるパラメータの更新などが記述されている. 今回はこの中身を説明することはしないが,興味のある読者は自身でソースコードを読んでみるとよい.

 をアップロード

simple_mnist.py をアップロードできたら,次に新しい notebook を作成しよう. "conda_pytorch_p36" の環境を選択することを忘れずに.

新しいノートブックが起動したら,まずは必要なライブラリをインポートしよう.

python
import torch
import torch.optim as optim
import torchvision
from torchvision import datasets, transforms
from matplotlib import pyplot as plt

# custom functions and classes
from simple_mnist import Model, train, evaluate
import torch
import torch.optim as optim
import torchvision
from torchvision import datasets, transforms
from matplotlib import pyplot as plt

# custom functions and classes
from simple_mnist import Model, train, evaluate

torchvision パッケージには,MNIST データセットをロードするなどの便利な関数が含まれている. また,今回のハンズオンで使うカスタムのクラス・関数 (Model, train, evaluate) のインポートを行っている.

次に,MNIST テストデータをダウンロードしよう. 同時に,画像データの輝度の正規化も行っている.

python
transf = transforms.Compose([transforms.ToTensor(),
                             transforms.Normalize((0.1307,), (0.3081,))])

trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transf)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)

testset = datasets.MNIST(root='./data', train=False, download=True, transform=transf)
testloader = torch.utils.data.DataLoader(testset, batch_size=1000, shuffle=True)
transf = transforms.Compose([transforms.ToTensor(),
                             transforms.Normalize((0.1307,), (0.3081,))])

trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transf)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)

testset = datasets.MNIST(root='./data', train=False, download=True, transform=transf)
testloader = torch.utils.data.DataLoader(testset, batch_size=1000, shuffle=True)

今回扱う MNIST データは 28x28 ピクセルの正方形の画像(モノクロ)と,それぞれのラベル(0 - 9 の数字)の組で構成されている. いくつかのデータを抽出して,可視化してみよう. figure_title のような出力が得られるはずである.

python
examples = iter(testloader)
example_data, example_targets = examples.next()

print("Example data size:", example_data.shape)

fig = plt.figure(figsize=(10,4))
for i in range(10):
    plt.subplot(2,5,i+1)
    plt.tight_layout()
    plt.imshow(example_data[i][0], cmap='gray', interpolation='none')
    plt.title("Ground Truth: {}".format(example_targets[i]))
    plt.xticks([])
    plt.yticks([])
plt.show()
examples = iter(testloader)
example_data, example_targets = examples.next()

print("Example data size:", example_data.shape)

fig = plt.figure(figsize=(10,4))
for i in range(10):
    plt.subplot(2,5,i+1)
    plt.tight_layout()
    plt.imshow(example_data[i][0], cmap='gray', interpolation='none')
    plt.title("Ground Truth: {}".format(example_targets[i]))
    plt.xticks([])
    plt.yticks([])
plt.show()

MNIST の手書き数字画像とその教師ラベル

次に, CNN のモデルを定義する.

python
model = Model()
model.to("cuda") # load to GPU
model = Model()
model.to("cuda") # load to GPU

今回使う Modelsimple_mnist.py の中で定義されている. このモデルは,figure_title に示したような,2層の畳み込み層と 2 層の全結合層からなるネットワークである. 出力層 (output layer) には Softmax 関数を使用し,損失関数 (Loss function) には 負の対数尤度関数 (Negative log likelyhood; NLL) を使用している.

本ハンズオンで使用するニューラルネットの構造.

続いて, CNN のパラメータを更新する最適化アルゴリズムを定義する. ここでは, 確率的勾配降下法 (Stochastic Gradient Descent; SGD) を使用している.

python
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)

これで,準備が整った. CNN の学習ループを開始しよう!

python
train_losses = []
for epoch in range(5):
    losses = train(model, trainloader, optimizer, epoch)
    train_losses = train_losses + losses
    test_loss, test_accuracy = evaluate(model, testloader)
    print(f"\nTest set: Average loss: {test_loss:.4f}, Accuracy: {test_accuracy:.1f}%\n")

plt.figure(figsize=(7,5))
plt.plot(train_losses)
plt.xlabel("Iterations")
plt.ylabel("Train loss")
plt.show()
train_losses = []
for epoch in range(5):
    losses = train(model, trainloader, optimizer, epoch)
    train_losses = train_losses + losses
    test_loss, test_accuracy = evaluate(model, testloader)
    print(f"\nTest set: Average loss: {test_loss:.4f}, Accuracy: {test_accuracy:.1f}%\n")

plt.figure(figsize=(7,5))
plt.plot(train_losses)
plt.xlabel("Iterations")
plt.ylabel("Train loss")
plt.show()

ここでは 5 エポック分の学習を行っている. GPU を使えば,これくらいの計算であれば 1 分程度で完了するだろう.

出力として, figure_title のようなプロットが得られるはずである. イテレーションを重ねるにつれて,損失関数 (Loss function) の値が減少している (=精度が向上している) ことがわかる.

学習の進行に対する Train loss の変化

出力にはテキスト形式で各エポック終了後のテストデータに対する精度も表示されている. 最終的には 98% 以上の極めて高い精度を実現できていることが確認できるだろう (figure_title).

学習したCNNのテストデータに対するスコア (5エポック後)

学習した CNN の推論結果を可視化してみよう. 次のコードを実行することで, figure_title のような出力が得られるだろう. この図で,下段右から二番目は,"1"に近い見た目をしているが,きちんと"9"と推論できている. なかなか賢い CNN を作り出すことができたようだ!

python
model.eval()

with torch.no_grad():
    output = model(example_data.to("cuda"))

fig = plt.figure(figsize=(10,4))
for i in range(10):
    plt.subplot(2,5,i+1)
    plt.tight_layout()
    plt.imshow(example_data[i][0], cmap='gray', interpolation='none')
    plt.title("Prediction: {}".format(output.data.max(1, keepdim=True)[1][i].item()))
    plt.xticks([])
    plt.yticks([])
plt.show()
model.eval()

with torch.no_grad():
    output = model(example_data.to("cuda"))

fig = plt.figure(figsize=(10,4))
for i in range(10):
    plt.subplot(2,5,i+1)
    plt.tight_layout()
    plt.imshow(example_data[i][0], cmap='gray', interpolation='none')
    plt.title("Prediction: {}".format(output.data.max(1, keepdim=True)[1][i].item()))
    plt.xticks([])
    plt.yticks([])
plt.show()

学習した CNN による,MNIST画像の推論結果

最後に,学習したニューラルネットワークのパラメータを mnist_cnn.pt というファイル名で保存しておこう. これで,将来いつでも今回学習したモデルを再現し,別の実験に使用することができる.

python
torch.save(model.state_dict(), "mnist_cnn.pt")
torch.save(model.state_dict(), "mnist_cnn.pt")

以上が, AWS クラウドの仮想サーバーを立ち上げ,最初のディープラーニングの計算を行う一連の流れである. MNIST 文字認識のタスクを行うニューラルネットを,クラウド上の GPU を使って高速に学習させ,現実的な問題を一つ解くことができたのである. 興味のある読者は,今回のハンズオンを雛形に,自分の所望の計算を走らせてみるとよいだろう.

スタックの削除

これにて,ハンズオン第二回の内容はすべて説明した. クラウドの利用料金を最小化するため,使い終わった EC2 インスタンスはすぐさま削除しよう.

ハンズオン第一回と同様に, AWS の CloudFormation コンソールか, AWS CLI により削除を実行する (詳細は スタックを削除 参照).

sh
$ cdk destroy
$ cdk destroy

スタックの削除は各自で必ず行うこと! 行わなかった場合,EC2 インスタンスの料金が発生し続けることになる! g4dn.xlarge は $0.71 / hour の料金設定なので,一日起動しつづけると約$17 の請求が発生することになる!

AWS のバジェットアラート

AWS の初心者が (あるいは経験者も) しばしば陥る失敗が,インスタンスの停止忘れなどで無駄なリソースがクラウドで放置されてしまい,巨大な額の請求が届く,というミスだ. 特に,開発を行っている間はこのような事態は起こりうるものだと思って,備えておかなければならない. このような事態を未然に防ぐため, AWS Budgets という機能が無料で提供されている. AWS Budgets を利用することで,月の利用金額がある閾値を超えた場合にユーザーにメールが送信される,などのアラートを設定することができる. 詳細な手順は AWS の公式ブログ "Getting Started with AWS Budgets" を参照のこと. 本書の読者も,ぜひこのタイミングでアラートを設定しておくことを推奨する.

Docker 入門

ここまでの章で扱ってきたハンズオンでは,単一のサーバーを立ち上げ,それに SSH でログインをして,コマンドを叩くことで計算を行ってきた. いわば,パーソナルコンピュータの延長のような形でクラウドを使ってきたわけである. このような,インターネットのどこからでもアクセスできるパーソナルコンピュータとしてのクラウドという使い方も,もちろん便利であるし,いろいろな応用の可能性がある. しかし,これだけではクラウドの本当の価値は十分に発揮されていないと言うべきだろう. クラウド概論 で述べたように,現代的なクラウドの一番の強みは自由に計算機の規模を拡大できることにある. すなわち,多数のサーバーを同時に起動し,複数のジョブを分散並列的に実行させることで大量のデータを処理してこそ,クラウドの本領が発揮されるのである.

本章からはじまる 3 章分 (Docker 入門, Hands-on #3: AWS で自動質問回答ボットを走らせる, Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する) を使って,クラウドを利用することでどのように大規模な計算システムを構築しビッグデータの解析に立ち向かうのか,その片鱗をお見せしたい. とくに,前章で扱った深層学習をどのようにビッグデータに適用していくかという点に焦点を絞って議論していきたい. そのための前準備として,本章では Docker とよばれる計算機環境の仮想化ソフトウェアを紹介する (figure_title). 現代のクラウドは Docker なしには成り立たないといっても過言ではないだろう. クラウドに限らず,ローカルで行う計算処理にも Docker は大変便利である. AWS からは少し話が離れるが,しっかりと理解して前に進んでもらいたい.

機械学習の大規模化

先ほどから"計算システムの大規模化"と繰り返し唱えているが,それは具体的にはどのようなものを指しているのか? ここでは大規模データを処理するための計算機システムを,機械学習を例にとって見てみよう.

クラウドで行う科学計算・機械学習 で紹介した GPT-3 のような,超巨大な数のパラメータを有する深層学習モデルを学習させたいとしよう. そのような計算を行いたい場合,一つのサーバーでは計算力が到底足りない. したがって,典型的には figure_title に示すような計算システムの設計がなされる. すなわち,大量の教師データを小さなチャンクとして複数のマシンに分散し,並列的にニューラルネットのパラメータを最適化していくという構造である.

複数の計算機を使った大規模な深層学習モデルの訓練

あるいは,学習済みのモデルを大量のデータに適用し,解析を行いたいとしよう. たとえば, SNS のプラットフォームで大量の画像が与えられて,それぞれの写真に何が写っているのかをラベルづけする,などのアプリケーションを想定できる. そのような場合は, figure_title のようなアーキテクチャが考えられるだろう. すなわち,大量のデータを複数のマシンで分割し,それぞれのマシンで推論の計算を行うというような構造である.

複数の計算機による深層学習モデルを使った推論計算

このような複数の計算機を同時に走らせるようなアプリケーションをクラウド上で実現するには,どのようにすればよいのだろうか?

重要なポイントとして, figure_titlefigure_title で起動している複数のマシンは,基本的に全く同一の OS・計算環境を有している点である. ここで,個人のコンピュータで行うようなインストールの操作を,各マシンで行うこともできるが,それは大変な手間であるし,メンテナンスも面倒だろう. すなわち,大規模な計算システムを構築するには,簡単に計算環境を複製できるような仕組みが必要であるということがわかる.

そのような目的を実現するために使われるのが, Docker とよばれるソフトウェアである.

Docker とは

Docker のアイコン

Docker とは, コンテナ (Container) とよばれる仮想環境下で,ホスト OS とは独立した別の計算環境を走らせるためのソフトウェアである. Docker を使うことで, OS を含めたすべてのプログラムをコンパクトにパッケージングすることが可能になる (パッケージされた一つの計算環境のことを **イメージ (Image)**とよぶ). Docker を使うことで,クラウドのサーバー上に瞬時に計算環境を複製することが可能になり, figure_title で見たような複数の計算機を同時に走らせるためのシステムが実現できる.

Docker は 2013 年に Solomon Hykes らを中心に開発され,それ以降爆発的に普及し,クラウドコンピューティングだけでなく,機械学習・科学計算の文脈などでも欠かすことのできないソフトウェアとなった. Docker はエンタープライズ向けの製品を除き無料で使用することができ,コアの部分は オープンソースプロジェクト として公開されている. Docker は Linux, Windows, Mac いずれの OS でも提供されている. 概念としては, Docker は仮想マシン (Virtual machine; VM) にとても近い. ここでは, VM との対比をしながら,Docker とはなにかを簡単に説明しよう.

仮想マシン (VM) とは,ホストとなるマシンの上に,仮想化された OS を走らせる技術である (figure_title). VM には ハイパーバイザー (Hypervisor) とよばれるレイヤーが存在する. Hypervisor はまず,物理的な計算機リソース (CPU, RAM, network など) を分割し,仮想化する. たとえば, ホストマシンに物理的な CPU が 4 コアあるとして,ハイパーバイザーはそれを (2,2) 個の組に仮想的に分割することができる. VM 上で起動する OS には,ハイパーバイザーによって仮想化されたハードウェアが割り当てられる. VM 上で起動する OS は基本的に完全に独立であり,たとえば OS-A は OS-B に割り当てられた CPU やメモリー領域にアクセスすることはできない (これを isolation とよぶ). VM を作成するための有名なソフトウェアとしては, VMwareVirtualBoxXen などがある. また,これまで触ってきた EC2 も,基本的に VM 技術を使うことで所望のスペックをもった仮想マシンがユーザーに提示される.

Docker も, VM と同様に,仮想化された OS をホストの OS 上に走らせるための技術である. VM に対し, Docker ではハードウェアレベルの仮想化は行われておらず,すべての仮想化はソフトウェアレベルで実現されている (figure_title). Docker で走る仮想 OS は,多くの部分をホストの OS に依存しており,結果として非常にコンパクトである. その結果, Docker で仮想 OS を起動するために要する時間は, VM に比べて圧倒的に早い. また, パッケージ化された環境 (=イメージ) のサイズも完全な OS に比べ圧倒的に小さくなるので,ネットワークを通じたやり取りが非常に高速化される点も重要である 加えて, VM のいくつかの実装では,メタル (仮想化マシンに対して,物理的なハードウェア上で直接起動する場合のこと) と比べ,ハイパーバイザーレイヤーでのオーバーヘッドなどにより性能が低下することが知られているが, Docker ではメタルとほぼ同様の性能を引き出すことができるとされている.

その他, VM との相違点などはたくさんあるのだが,ここではこれ以上詳細には立ち入らない. 大事なのは, Docker とはとてもコンパクトかつハイパフォーマンスな仮想計算環境を作るツールである,という点である. その手軽さゆえに,2013 年の登場以降,クラウドシステムでの利用が急速に増加し,現代のクラウドでは欠くことのできない中心的な技術になっている.

Docker (左) と VM (右) の比較 (画像出典: https://www.docker.com/blog/containers-replacing-virtual-machines/)

職業的プログラマーにとっての"三種の神器"とはなんだろうか? 多様な意見があると思うが,筆者は Git, Vim そして Docker を挙げたい.

Git は多くの読者がご存じの通り,コードの変更を追跡するためのシステムである. Linux の作成者である Linus Torvalds によって 2005 年に誕生した. チームでの開発を進める際には欠かせないツールだ.

Vim は 1991 年から 30 年以上の間プログラマーたちに愛されてきたテキストエディターである. Stackoverflow が行った 2019 年のアンケート によると,開発環境の部門で 5 位の人気を獲得している. たくさんのショートカットと様々なカスタム設定が提供されているので,初見の人にはなかなかハードルが高いが,一度マスターすれば他のモダンなエディターや統合開発環境に負けない,あるいはそれ以上の開発体験を実現することができる.

これらの十年以上の歴史あるツールに並んで,第三番目の三種の神器として挙げたいのが Docker だ. Docker はプログラマーの開発のワークフローを一変させた. たとえば,プロジェクトごとに Docker イメージを作成することで,どの OS・コンピュータ でも全く同じ計算環境で開発・テストを実行することができるようになった. また, DevOpsCI / CD (Continuous Integration / Continuous Deployment) といった最近の開発ワークフローも Docker のようなコンテナ技術の存在に立脚している. さらにはサーバーレスコンピューティング (Serverless architecture) といった概念も,コンテナ技術の生んだ大きな技術革新といえる.

あなたにとっての三種の神器はなんだろうか? また,これからの未来ではどんな新しいツールが三種の神器としてプログラマーのワークフローを革新していくだろうか?

Docker チュートリアル

Docker とはなにかを理解するためには,実際に触って動かしてみるのが一番有効な手立てである. ここでは, Docker の簡単なチュートリアルを行っていく.

Docker のインストールについては, Docker のインストール および 公式のドキュメンテーション を参照してもらいたい. Docker のインストールが完了している前提で,以下は話を進めるものとする.

Docker 用語集

Docker を使い始めるに当たり,最初に主要な用語を解説しよう. 次のパラグラフで太字で強調された用語を頭に入れた上で,続くチュートリアルに取り組んでいただきたい.

Docker を起動する際の大まかなステップを示したのが figure_title である. パッケージされた一つの計算環境のことを **イメージ (Image)**とよぶ. イメージは, Docker Hub などのリポジトリで配布されているものをダウンロードするか,自分でカスタムのイメージを作成することも可能である. イメージを作成するための”レシピ”を記述したファイルが Dockerfile である. Dockerfile からイメージを作成する操作を build とよぶ. イメージがホストマシンのメモリにロードされ,起動状態にある計算環境のことを コンテナ (Container) とよぶ. Container を起動するために使用されるコマンドが run である.

Image と Container

イメージをダウンロード

パッケージ化された Docker の仮想環境 (= イメージ (Image)) は, Docker Hub からダウンロードできる. Docker Hub には,個人や企業・団体が作成した Docker イメージが集められており, GitHub などと同じ感覚で,オープンな形で公開されている.

たとえば, Ubuntu のイメージは Ubuntu の公式リポジトリ で公開されており, pull コマンドを使うことでローカルにダウンロードすることができる.

sh
$ docker pull ubuntu:18.04
$ docker pull ubuntu:18.04

ここで,イメージ名の : (コロン) 以降に続く文字列を タグ (tag) と呼び,主にバージョンを指定するなどの目的で使われる.

pull コマンドはデフォルトでは Docker Hub でイメージを検索し,ダウンロードを行う. Docker イメージを公開するためのデータベース (レジストリ (registry) とよぶ) は Docker Hub だけではなく,たとえば GitLab や GitHub は独自のレジストリ機能を提供しているし,個人のサーバーでレジストリを立ち上げることも可能である. Docker Hub 以外のレジストリから pull するには, myregistry.local:5000/testing/test-image のように,イメージ名の先頭につける形でレジストリのアドレス (さらにオプションとしてポート番号) を指定する.

コンテナを起動

Pull してきたイメージを起動するには, run コマンドを使う.

sh
$ docker run -it ubuntu:18.04
$ docker run -it ubuntu:18.04

ここで, -it とは,インタラクティブな shell のセッションを開始するために必要なオプションである.

このコマンドを実行すると,仮想化された Ubuntu が起動され,コマンドラインからコマンドが打ち込めるようになる (figure_title). このように起動状態にある計算環境 (ランタイム) のことを Container (コンテナ) とよぶ.

Docker を使って ubuntu:18.04 イメージを起動

ここで使用した ubuntu:18.04 のイメージは,空の Ubuntu OS だが,すでにプログラムがインストール済みのものもある. これは, Hands-on #2: AWS でディープラーニングを実践 でみた DLAMI と概念として似ている. たとえば, PyTorch がインストール済みのイメージは PyTorch 公式の Docker Hub リポジトリ で公開されている.

これを起動してみよう.

sh
$ docker run -it pytorch/pytorch
$ docker run -it pytorch/pytorch

docker run を実行したとき,ローカルに該当するイメージが見つからない場合は,自動的に Docker Hub からダウンロードされる.

pytorch のコンテナが起動したら, Python のシェルを立ち上げて, pytorch をインポートしてみよう.

sh
$ python3
Python 3.7.7 (default, May  7 2020, 21:25:33)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.cuda.is_available()
False
$ python3
Python 3.7.7 (default, May  7 2020, 21:25:33)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.cuda.is_available()
False

このように, Docker を使うことで簡単に特定の OS・プログラムの入った計算環境を再現することが可能になる.

自分だけのイメージを作る

自分の使うソフトウェア・ライブラリがインストールされた,自分だけのイメージを作ることも可能である.

たとえば, 本書のハンズオン実行用に提供している docker イメージ には, Python, Node.js, AWS CLI, AWS CDK などのソフトウェアがインストール済みであり,ダウンロードしてくるだけですぐにハンズオンのプログラムが実行できるようになっている.

カスタムの docker イメージを作るには, Dockerfile という名前のついたファイルを用意し,その中にどんなプログラムをインストールするかなどを記述していく.

具体例として,本書で提供している Docker イメージのレシピを見てみよう (docker/Dockerfile).

python
FROM node:12
LABEL maintainer="Tomoyuki Mano"

RUN apt-get update \
    && apt-get install nano

#
RUN cd /opt \
    && curl -q "https://www.python.org/ftp/python/3.7.6/Python-3.7.6.tgz" -o Python-3.7.6.tgz \
    && tar -xzf Python-3.7.6.tgz \
    && cd Python-3.7.6 \
    && ./configure --enable-optimizations \
    && make install

RUN cd /opt \
    && curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" \
    && unzip awscliv2.zip \
    && ./aws/install

#
RUN npm install -g aws-cdk@1.100

# clean up unnecessary files
RUN rm -rf /opt/*

# copy hands-on source code in /root/
COPY handson/ /root/handson
FROM node:12
LABEL maintainer="Tomoyuki Mano"

RUN apt-get update \
    && apt-get install nano

#
RUN cd /opt \
    && curl -q "https://www.python.org/ftp/python/3.7.6/Python-3.7.6.tgz" -o Python-3.7.6.tgz \
    && tar -xzf Python-3.7.6.tgz \
    && cd Python-3.7.6 \
    && ./configure --enable-optimizations \
    && make install

RUN cd /opt \
    && curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" \
    && unzip awscliv2.zip \
    && ./aws/install

#
RUN npm install -g aws-cdk@1.100

# clean up unnecessary files
RUN rm -rf /opt/*

# copy hands-on source code in /root/
COPY handson/ /root/handson

Dockerfile の中身の説明は詳しくは行わないが,たとえば上のコードで <1> で示したところは, Python 3.7 のインストールを実行している. また, <2> で示したところは, AWS CDK のインストールを行っていることがわかるだろう. このように,リアルな OS で行うのと同じ流れでインストールのコマンドを逐一記述していくことで,自分だけの Docker イメージを作成することができる. 一度イメージを作成すれば,それを配布することで,他者も同一の計算環境を簡単に再構成することができる.

"ぼくの環境ではそのプログラム走ったのにな…" というのは,プログラミング初心者ではよく耳にする会話だが, Docker を使いこなせばそのような心配とは無縁である. そのような意味で,クラウド以外の場面でも, Docker の有用性・汎用性は極めて高い.

コンテナを用いた仮想計算環境ツールとして Docker を紹介したが, ほかに選択肢はないのか? よくぞ聞いてくれた! Docker の登場以降,複数のコンテナベースの仮想環境ツールが開発されてきた. いずれのツールも,概念や API については Docker と共通するものが多いが,Docker にはない独自の特徴を提供している. ここではその中でも有名ないくつかを紹介しよう.

Singularity は科学計算や HPC (High Performance Computing) の分野で人気の高いコンテナプラットフォームである. Singularity では大学・研究機関の HPC クラスターでの運用に適したような設計が施されている. たとえば, Docker は基本的には root 権限で実行されるのに対し, Singularity はユーザー権限 (コマンドを実行したユーザー自身) でプログラムが実行される. root 権限での実行は Web サーバーのように個人・企業がある特定のサービスのために運用するサーバーでは問題ないが,多数のユーザーが多様な目的で計算を実行する HPC クラスターでは問題となる. また,Singularity は独自のイメージの作成方法・エコシステムをもっているが, Docker イメージを Singularity のイメージに変換し実行する機能も有している.

podman は Red Hat 社によって開発されたもう一つのコンテナプラットフォームである. podman は基本的に Docker と同一のコマンドを採用しているが,実装は Red Hat によってスクラッチから行われた. podman では, Singularity と同様にユーザー権限でのプログラムの実行を可能であり,クラウドおよび HPC の両方の環境に対応するコンテナプラットフォームを目指して作られた. また,その名前にあるとおり pod とよばれる独自の概念が導入されている.

著者の個人的な意見としては,現時点では Docker をマスターしておけば当面は困ることはないと考えるが,興味のある読者はぜひこれらのツールも試してみてはいかがだろうか?

Elastic Container Service (ECS)

ECS のアイコン

ここまでに説明してきたように, Docker を使うことで仮想計算環境を簡単に複製・起動することが可能になる. 本章の最後の話題として, AWS 上で Docker を使った計算システムを構築する方法を解説しよう.

Elastic Container Service (ECS) とは, Docker を使った計算機クラスターを AWS 上に作成するためのツールである (figure_title). ECS を使用することで, Docker にパッケージされたアプリケーションを計算機クラスターに投入したり,計算機クラスターのインスタンスを追加・削除する操作 (=スケーリング) を行うことができる.

ECS の概要を示したのが figure_title である. ECS は,タスク (Task) と呼ばれる単位で管理された計算ジョブを受け付ける. システムにタスクが投入されると,ECS は最初にタスクで指定された Docker イメージを外部レジストリからダウンロードしてくる. 外部レジストリとしては, Docker Hub や AWS 独自の Docker レジストリである ECR (Elastic Container Registry) を指定することができる.

ECS の次の重要な役割はタスクの配置である. あらかじめ定義されたクラスター内で,計算負荷が小さい仮想インスタンスを選び出し,そこに Docker イメージを配置することで指定された計算タスクが開始される. "計算負荷が小さい仮想インスタンスを選び出す" と言ったが,具体的にどのような戦略・ポリシーでこの選択を行うかは,ユーザーの指定したパラメータに従う.

また,クラスターのスケーリングも ECS における重要な概念である. スケーリングとは,クラスター内のインスタンスの計算負荷をモニタリングし,計算負荷に応じてインスタンスの起動・停止を行う操作を指す. クラスター全体の計算負荷が指定された閾値 (たとえば 80%の稼働率) を超えていた場合,新たな仮想インスタンスをクラスター内に立ち上げる操作を scale-out (スケールアウト) とよび, 負荷が減った場合に不要なインスタンスを停止する操作を scale-in (スケールイン) とよぶ. クラスターのスケーリングは, ECS がほかの AWS のサービスと連携することで実現される. 具体的には, EC2 の Auto scaling group (ASG)Fargate の2つの選択肢が多くの場合選択される. ASG については Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する, Fargate については Hands-on #3: AWS で自動質問回答ボットを走らせる でより詳細に解説する.

これら一連のタスクの管理を, ECS は自動でやってくれる. クラスターのスケーリングやタスクの配置に関してのパラメータを一度指定してしまえば,ユーザーは (ほとんどなにも考えずに) 大量のタスクを投入することができる. クラスターのスケーリングによってタスクの量にちょうど十分なだけのインスタンスが起動し,タスクが完了した後は不要なインスタンスはすべて停止される.

さて,ここまで説明的な話が続いてしまったが,次章からは早速 Docker と AWS を使って大規模な並列計算システムを構築していこう!

ECS の概要

Hands-on #3: AWS で自動質問回答ボットを走らせる

ハンズオン第三回では, Docker と ECS を駆使した機械学習アプリケーションを実装しよう. 具体的には,深層学習による自然言語処理を行うことで,クライアントから与えられた文章題に対して回答を生成する,自動 Question & Answering ボットを作成しよう. ECS を利用することで,ジョブの数によって動的にインスタンスの数を制御し,並列にタスクを実行するようなシステムを構築しよう.

通常の機械学習のワークフローでは,モデルの訓練 ⇒ 推論 (データへの適用) が基本的な流れである. しかしながら, GPU 搭載型の EC2 クラスターを使ったモデルの訓練はやや難易度が高いため,次章 (Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する) で取り扱う. 本章は,クラウド上でのクラスターの構築・タスクの管理などの概念に慣れるため,よりシンプルな実装で実現できる Fargate クラスターを用いた推論計算の並列化を紹介する.

Fargate

ハンズオンに入っていく前に, Fargate という AWS の機能を知っておく必要がある (figure_title).

Fargate のアイコン

ECS の概要を示した figure_title をもう一度見てみよう. この図で, ECS の管理下にあるクラスターが示されているが,このクラスターの中で計算を行う実体としては二つの選択肢がある. EC2 あるいは Fargate のいずれかである. EC2 を用いた場合は,先の章 (Hands-on #1: 初めての EC2 インスタンスを起動する, Hands-on #2: AWS でディープラーニングを実践) で説明したような流れでインスタンスが起動し,計算が実行される. しかし, EC2 を用いた計算機クラスターの作成・管理は技術的な難易度がやや高いので,次章 (Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する) で説明することにする.

Fargate とは, ECS での利用に特化して設計された,コンテナを使用した計算タスクを走らせるための仕組みである. 計算を走らせるという点では EC2 と役割は似ているが, Fargate は EC2 インスタンスのような物理的実体はもたない. 物理的実体をもたないというのは,たとえば SSH でログインすることは基本的に想定されていないし,なにかのソフトウェアをインストールしたりなどの概念も存在しない. Fargate ではすべての計算は Docker コンテナを介して行われる. すなわち, Fargate を利用するには,ユーザーは最初に所望の Docker イメージを指定しておき, Fargate は docker run のコマンドを使用することで計算タスクを実行する. Fargate を用いる利点は, Fargate を ECS のクラスターに指定すると,スケーリングなどの操作が簡単な設定・プログラムで構築できる点である.

Fargate では, EC2 と同様に CPU とメモリーのサイズを必要な分だけ指定できる. 執筆時点では, CPU は 0.25 - 4 コア, RAM は 0.5 - 30 GB の間で選択することができる (詳しくは 公式ドキュメンテーション "Amazon ECS on AWS Fargate" 参照). クラスターのスケーリングが容易な分, Fargate では EC2 ほど大きな CPU コア・ RAM 容量を単一インスタンスに付与することができず,また GPU を利用することもできない.

以上が Fargate の概要であったが,くどくど言葉で説明してもなかなかピンとこないだろう. ここからは実際に手を動かしながら, ECS と Fargate を使った並列タスクの処理の仕方を学んでいこう.

厳密には, ECS に付与するクラスターには EC2 と Fargate のハイブリッドを使用することも可能である.

準備

ハンズオンのソースコードは GitHub の handson/qa-bot にある.

本ハンズオンの実行には,第一回ハンズオンで説明した準備 (準備) が整っていることを前提とする. また, Docker が自身のローカルマシンにインストール済みであることも必要である.

このハンズオンでは 1CPU/4GB RAM の Fargate インスタンスを使用する. 計算の実行には 0.025 $/hour のコストが発生することに注意.

Transformer を用いた question-answering プログラム

このハンズオンで開発する,自動質問回答システムをより具体的に定義しよう. 次のような文脈 (context) と質問 (question) が与えられた状況を想定する.

txt
context: Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist who developed the theory of relativity, one of the two pillars of modern physics (alongside quantum mechanics). His work is also known for its influence on the philosophy of science. He is best known to the general public for his mass–energy equivalence formula E = mc2, which has been dubbed \"the world's most famous equation\". He received the 1921 Nobel Prize in Physics \"for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect\", a pivotal step in the development of quantum theory.

question: In what year did Einstein win the Nobel prize?
context: Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist who developed the theory of relativity, one of the two pillars of modern physics (alongside quantum mechanics). His work is also known for its influence on the philosophy of science. He is best known to the general public for his mass–energy equivalence formula E = mc2, which has been dubbed \"the world's most famous equation\". He received the 1921 Nobel Prize in Physics \"for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect\", a pivotal step in the development of quantum theory.

question: In what year did Einstein win the Nobel prize?

今回作成する自動回答システムは,このような問題に対して, context に含まれる文字列から正解となる言葉を見つけ出すものとする. 上の問題では,次のような回答を返すべきである.

sh
answer: 1921
answer: 1921

人間にとっては,このような文章を理解することは容易であるが,コンピュータにそれを解かせるのは難しいことは容易に想像ができるだろう. しかし,近年の深層学習を使った自然言語処理の進歩は著しく,上で示したような例題などは極めて高い正答率で回答できるモデルを作ることができる.

今回は, huggingface/transformers で公開されている学習済みの言語モデルを利用することで,上で定義した問題を解く Q&A ボットを作る. この Q&A ボットは Transformer とよばれるモデルを使った自然言語処理に支えられえている (figure_title). このプログラムを, Docker にパッケージしたものが 著者の Docker Hub リポジトリ に用意してある. クラウドの設計に入る前に,まずはこのプログラムを単体で動かしてみよう.

Transformer モデルアーキテクチャ (画像出典: Vaswani+ 2017)

なお,今回は学習済みのモデルを用いているので,私達が行うのは与えられた入力をモデルに投入して予測を行う (推論) のみである. 推論の演算は, CPU だけでも十分高速に行うことができるので,コストの削減と,実装をシンプルにする目的で,このハンズオンでは GPU は利用しない. 一般的に, ニューラルネットは学習のほうが圧倒的に計算コストが大きく,そのような場合に GPU はより威力を発揮する.

次のコマンドで,今回使う Docker image を ローカルにダウンロード (pull) してこよう.

sh
$ docker pull tomomano/qabot:latest
$ docker pull tomomano/qabot:latest

pull できたら,早速この Docker に質問を投げかけてみよう. まずは context と question をコマンドラインの変数として定義する.

sh
$ context="Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist who developed the theory of relativity, one of the two pillars of modern physics (alongside quantum mechanics). His work is also known for its influence on the philosophy of science. He is best known to the general public for his mass–energy equivalence formula E = mc2, which has been dubbed the world's most famous equation. He received the 1921 Nobel Prize in Physics for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect, a pivotal step in the development of quantum theory."
$ question="In what year did Einstein win the Nobel prize ?"
$ context="Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist who developed the theory of relativity, one of the two pillars of modern physics (alongside quantum mechanics). His work is also known for its influence on the philosophy of science. He is best known to the general public for his mass–energy equivalence formula E = mc2, which has been dubbed the world's most famous equation. He received the 1921 Nobel Prize in Physics for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect, a pivotal step in the development of quantum theory."
$ question="In what year did Einstein win the Nobel prize ?"

そうしたら,次のコマンドによってコンテナを実行する.

sh
$ docker run tomomano/qabot "${context}" "${question}" foo --no_save
$ docker run tomomano/qabot "${context}" "${question}" foo --no_save

今回用意した Docker image は,第一引数に context となる文字列を,第二引数に question に相当する文字列を受けつける. 第三引数,第四引数については,クラウドに展開するときの実装上の都合なので,いまは気にしなくてよい.

このコマンドを実行すると,次のような出力が得られるはずである.

sh
{'score': 0.9881729286683587, 'start': 437, 'end': 441, 'answer': '1921'}
{'score': 0.9881729286683587, 'start': 437, 'end': 441, 'answer': '1921'}

"score" は正解の自信度を表す数字で, [0,1] の範囲で与えられる. "start", "end" は, context 中の何文字目が正解に相当するかを示しており, "answer" が正解と予測された文字列である. 1921 年という,正しい答えが返ってきていることに注目してほしい.

もう少し難しい質問を投げかけてみよう.

sh
$ question="Why did Einstein win the Nobel prize ?"
$ docker run tomomano/qabot "${context}" "${question}" foo --no_save
$ question="Why did Einstein win the Nobel prize ?"
$ docker run tomomano/qabot "${context}" "${question}" foo --no_save

出力:

sh
{'score': 0.5235594527494207, 'start': 470, 'end': 506, 'answer': 'his services to theoretical physics,'}
{'score': 0.5235594527494207, 'start': 470, 'end': 506, 'answer': 'his services to theoretical physics,'}

今度は, score が 0.52 と,少し自信がないようだが,それでも正しい答えにたどりつけていることがわかる.

このように, 深層学習に支えられた言語モデルを用いることで,実用にも役に立ちそうな Q&A ボットを実現できていることがわかる. 以降では,このプログラムをクラウドに展開することで,大量の質問に自動で対応できるようなシステムを設計していく.

今回使用する Question & Answering システムには, DistilBERT という Transformer を基にした言語モデルが用いられている. 興味のある読者は, 原著論文 を参照してもらいたい. また, huggingface/transformers による DistilBert の実装のドキュメンテーションは 公式ドキュメンテーション を参照のこと.

今回提供する Q-A ボットの Docker のソースコードは https://github.com/andatoshiki/toshiki-notebookblob/main/handson/qa-bot/docker/Dockerfile にある.

アプリケーションの説明

このハンズオンで作成するアプリケーションの概要を figure_title に示す.

アプリケーションのアーキテクチャ

簡単にまとめると,以下のような設計である.

  • クライアントは,質問を AWS 上のアプリケーションに送信する.

  • 質問のタスクは ECS によって処理される.

  • ECS は, Docker Hub から,イメージをダウンロードする.

  • 次に,ECS はクラスター内に新たな Fargate インスタンスを立ち上げ,ダウンロードされた Docker イメージをこの新規インスタンスに配置する.

    • このとき,一つの質問に対し一つの Fargate インスタンスを立ち上げることで,複数の質問を並列的に処理できるようにする.
  • ジョブが実行される.

  • ジョブの実行結果 (質問への回答) は, データベース (DynamoDB) に書き込まれる.

  • 最後に,クライアントは DynamoDB から質問への回答を読み取る.

それでは,プログラムのソースコードを見てみよう (handson/qa-bot/app.py).

sh
class EcsClusterQaBot(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        # dynamoDB table to store questions and answers
        table = dynamodb.Table(
            self, "EcsClusterQaBot-Table",
            partition_key=dynamodb.Attribute(
                name="item_id", type=dynamodb.AttributeType.STRING
            ),
            billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        #
        vpc = ec2.Vpc(
            self, "EcsClusterQaBot-Vpc",
            max_azs=1,
        )

        #
        cluster = ecs.Cluster(
            self, "EcsClusterQaBot-Cluster",
            vpc=vpc,
        )

        #
        taskdef = ecs.FargateTaskDefinition(
            self, "EcsClusterQaBot-TaskDef",
            cpu=1024, # 1 CPU
            memory_limit_mib=4096, # 4GB RAM
        )

        # grant permissions
        table.grant_read_write_data(taskdef.task_role)
        taskdef.add_to_task_role_policy(
            iam.PolicyStatement(
                effect=iam.Effect.ALLOW,
                resources=["*"],
                actions=["ssm:GetParameter"]
            )
        )

        #
        container = taskdef.add_container(
            "EcsClusterQaBot-Container",
            image=ecs.ContainerImage.from_registry(
                "tomomano/qabot:latest"
            ),
        )
class EcsClusterQaBot(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        # dynamoDB table to store questions and answers
        table = dynamodb.Table(
            self, "EcsClusterQaBot-Table",
            partition_key=dynamodb.Attribute(
                name="item_id", type=dynamodb.AttributeType.STRING
            ),
            billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        #
        vpc = ec2.Vpc(
            self, "EcsClusterQaBot-Vpc",
            max_azs=1,
        )

        #
        cluster = ecs.Cluster(
            self, "EcsClusterQaBot-Cluster",
            vpc=vpc,
        )

        #
        taskdef = ecs.FargateTaskDefinition(
            self, "EcsClusterQaBot-TaskDef",
            cpu=1024, # 1 CPU
            memory_limit_mib=4096, # 4GB RAM
        )

        # grant permissions
        table.grant_read_write_data(taskdef.task_role)
        taskdef.add_to_task_role_policy(
            iam.PolicyStatement(
                effect=iam.Effect.ALLOW,
                resources=["*"],
                actions=["ssm:GetParameter"]
            )
        )

        #
        container = taskdef.add_container(
            "EcsClusterQaBot-Container",
            image=ecs.ContainerImage.from_registry(
                "tomomano/qabot:latest"
            ),
        )
  • ここでは,回答の結果を書き込むためのデータベースを用意している. DynamoDB については,サーバーレスアーキテクチャの章で扱うので,今は気にしなくてよい.

  • ここでは,ハンズオン #1, #2 で行ったのと同様に, VPC を定義している.

  • ここで, ECS のクラスター (cluster) を定義している. クラスターとは,仮想サーバーのプールのことであり,クラスターの中に複数の仮想インスタンスを配置する.

  • ここで,実行するタスクを定義している (task definition).

  • ここで, タスクの実行で使用する Docker イメージを定義している.

ECS と Fargate

ECS と Fargate の部分について,コードをくわしく見てみよう.

sh
cluster = ecs.Cluster(
    self, "EcsClusterQaBot-Cluster",
    vpc=vpc,
)

taskdef = ecs.FargateTaskDefinition(
    self, "EcsClusterQaBot-TaskDef",
    cpu=1024, # 1 CPU
    memory_limit_mib=4096, # 4GB RAM
)

container = taskdef.add_container(
    "EcsClusterQaBot-Container",
    image=ecs.ContainerImage.from_registry(
        "tomomano/qabot:latest"
    ),
)
cluster = ecs.Cluster(
    self, "EcsClusterQaBot-Cluster",
    vpc=vpc,
)

taskdef = ecs.FargateTaskDefinition(
    self, "EcsClusterQaBot-TaskDef",
    cpu=1024, # 1 CPU
    memory_limit_mib=4096, # 4GB RAM
)

container = taskdef.add_container(
    "EcsClusterQaBot-Container",
    image=ecs.ContainerImage.from_registry(
        "tomomano/qabot:latest"
    ),
)

cluster = の箇所で,空の ECS クラスターを定義している.

次に, taskdef=ecs.FargateTaskDefinition の箇所で, Fargate インスタンスを使ったタスクを定義しており,とくにここでは 1 CPU, 4GB RAM というマシンスペックを指定している. また,このようにして定義されたタスクは,デフォルトで 1 タスクにつき 1 インスタンスが使用される.

最後に, container = の箇所で,タスクの実行で使用する Docker image を定義している. ここでは, Docker Hub に置いてある image をダウンロードしてくるよう指定している.

このようにわずか数行のコードであるが,これだけで前述したような,タスクのスケジューリングなどが自動で実行される.

このコードで cpu=1024 と指定されているのに注目してほしい. これは CPU ユニットと呼ばれる数で, 以下の換算表に従って仮想 CPU (virtual CPU; vCPU) が割り当てられる. 1024 が 1 CPU に相当する. 0.25 や 0.5 vCPU などの数字は,それぞれ実効的に 1/4, 1/2 の CPU 時間が割り当てられることを意味する. また, CPU ユニットによって使用できるメモリー量も変わってくる. たとえば, 1024 CPU ユニットを選択した場合は, 2 から 8 GB の範囲でのみメモリー量を指定することができる. 最新の情報は 公式ドキュメンテーション "Amazon ECS on AWS Fargate" を参照のこと.

CPU ユニットと 指定可能なメモリー量の換算表

CPU ユニット

メモリーの値

256 (.25 vCPU)

0.5 GB, 1 GB, 2 GB

512 (.5 vCPU)

1 GB, 2 GB, 3 GB, 4 GB

1024 (1 vCPU)

2 GB, 3 GB, 4 GB, 5 GB, 6 GB, 7 GB, 8 GB

2048 (2 vCPU)

Between 4 GB and 16 GB in 1-GB increments

4096 (4 vCPU)

Between 8 GB and 30 GB in 1-GB increments

スタックのデプロイ

スタックの中身が理解できたところで,早速スタックをデプロイしてみよう.

デプロイの手順は,これまでのハンズオンとほとんど共通である. SSH によるログインの必要がないので,むしろ単純なくらいである. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). それぞれの意味を忘れてしまった場合は,ハンズオン 1, 2 に戻って復習していただきたい. シークレットキーの設定も忘れずに (AWS CLI のインストール).

sh
# プロジェクトのディレクトリに移動
$ cd handson/qa-bot

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd handson/qa-bot

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイのコマンドが無事に実行されれば, figure_title のような出力が得られるはずである.

CDKデプロイ実行後の出力

AWS コンソールにログインして,デプロイされたスタックの中身を確認してみよう. コンソールから,ECS のページに行くと figure_title のような画面が表示されるはずである. EcsClusterQaBot-XXXX という名前ついたクラスターを見つけよう.

Cluster というのが,先ほど説明したとおり,複数の仮想インスタンスを束ねる一つの単位である. figure_title で, FARGATE という文字の下に 0 Running tasks, 0 Pending tasks と表示されていることを確認しよう. この時点では一つもタスクが走っていないので,数字はすべて 0 になっている.

ECS コンソール画面

続いて,この画面の左のメニューバーから Task Definitions という項目を見つけ,クリックしよう. 移動した先のページで EcsClusterQaBotEcsClusterQaBotTaskDefXXXX という項目が見つかるので,開く. 開いた先のページをスクロールすると figure_title に示したような情報が見つかるだろう. 使用する CPU ・メモリーの量や, Docker container の実行に関する設定などが,この Task Definition の画面から確認することができる.

Task definition の確認

タスクの実行

それでは,質問をデプロイしたクラウドに提出してみよう.

ECS にタスクを投入するのはやや複雑なので,タスクの投入を簡単にするプログラム (run_task.py) を用意した (handson/qa-bot/run_task.py).

次のようなコマンドで,ECS クラスターに新しい質問を投入することができる.

sh
$ python run_task.py ask "A giant peach was flowing in the river. She picked it up and brought it home. Later, a healthy baby was born from the peach. She named the baby Momotaro." "What is the name of the baby?"
$ python run_task.py ask "A giant peach was flowing in the river. She picked it up and brought it home. Later, a healthy baby was born from the peach. She named the baby Momotaro." "What is the name of the baby?"

run_task.py を実行するには, コマンドラインで AWS の認証情報が設定されていることが前提である.

"ask" の引数に続き,文脈 (context) と質問 (question) を引数として渡している.

このコマンドを実行すると, "Waiting for the task to finish…" と出力が表示され,回答を得るまでしばらく待たされる. この間, AWS では ECS がタスクを受理し,新しい Fargate のインスタンスを起動し, Docker イメージをそのインスタンスに配置する,という一連の処理がなされている. AWS コンソールから,この一連の様子をモニタリングしてみよう.

先ほどの ECS コンソール画面にもどり,クラスターの名前をクリックすることで,クラスターの詳細画面を開く. 次に, "Tasks" という名前のタブがあるので,それを開く (figure_title). すると,実行中のタスクの一覧が表示されるだろう.

ECS のタスクの実行状況をモニタリング

figure_title で見て取れるように, "Last status = Pending" となっていることから,この時点では,タスクを実行する準備をしている段階である,ということがわかる. Fargate のインスタンスを起動し, Docker image を配置するまでおよそ 1-2 分の時間がかかる.

しばらく待つうちに, Status が "RUNNING" に遷移し,計算が始まる. 計算が終わると, Status は "STOPPED" に遷移し, ECS によって Fargate インスタンスは自動的にシャットダウンされる.

figure_title の画面から, "Task" の列にあるタスク ID クリックすることで,タスクの詳細画面を開いてみよう (figure_title). "Last status", "Platform version" など,タスクの情報が表示されている. また, "Logs" のタブを開くことで,コンテナの吐き出した実行ログを閲覧することができる.

質問タスクの実行結果

さて, run_task.py を実行したコマンドラインに戻ってきてみると, figure_title のような出力が得られているはずである. "Momotaro" という正しい回答が返ってきている!

質問タスクの実行結果

タスクの同時実行

さて,先ほどはたった一つの質問を投入したわけだが,今回設計したアプリケーションは, ECS と Fargate を使うことで同時にたくさんの質問を処理することができる. 実際に,たくさんの質問を一度に投入してみよう. run_task.pyask_many というオプションを付けることで,複数の質問を一度に送信できる. 質問の内容は handson/qa-bot/problems.json に定義されている.

次のようなコマンドを実行しよう.

sh
$ python run_task.py ask_many
$ python run_task.py ask_many

このコマンドを実行した後で,先ほどの ECS コンソールに行き,タスクの一覧を見てみよう (figure_title). 複数の Fargate インスタンスが起動され,タスクが並列に実行されているのがわかる.

複数の質問タスクを同時に投入する

すべてのタスクのステータスが "STOPPED" になったことを確認した上で,質問への回答を取得しよう. それには,次のコマンドを実行する.

sh
$ python run_task.py list_answers
$ python run_task.py list_answers

結果として, figure_title のような出力が得られるだろう. 複雑な文章問題に対し,高い正答率で回答できていることがわかるだろう.

 の実行結果

おめでとう! ここまでついてこれた読者はとても初歩的ながらも,深層学習による言語モデルを使って自動で質問への回答を生成するシステムを創り上げることができた! それも,数百の質問にも同時に対応できるような,とても高いスケーラビリティーをもったシステムである! 今回は GUI (Graphical User Interface) を用意することはしなかったが,このシステムに簡単な GUI を追加すればなかなか立派なウェブサービスとして運用できるだろう.

run_task.py で質問を投入し続けると,回答を記録しているデータベースにどんどんエントリーが溜まっていく. これらのエントリーをすべて消去するには,次のコマンドを使う.

sh
$ python run_task.py clear
$ python run_task.py clear

スタックの削除

これにて,今回のハンズオンは終了である. 最後にスタックを削除しよう.

スタックを削除するには,前回までと同様に, AWS コンソールにログインし CloudFormation の画面から DELETE ボタンをクリックするか,コマンドラインからコマンドを実行する. コマンドラインから行う場合は,次のコマンドを使用する.

sh
$ cdk destroy
$ cdk destroy

Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する

ハンズオン第三回では, ECS と Fargate を使って自動質問回答システムを構築した. シンプルながらも,複数の質問が送られた場合には並列にジョブが実行され,ユーザーに答えが返されるシステムを作ることができた. ここでは,すでに学習済みの言語モデルを用いてアプリケーションを構築した. しかし,一般的に言って,機械学習のワークフローでは自分で作ったモデルを訓練することが最初のステップにあるはずである. そこで,ハンズオン第四回では,クラウドを用いて機械学習の訓練を並列化・高速化することを考える.

本ハンズオンでは深層学習におけるハイパーパラメータ最適化を取り上げる. ハイパーパラメータとは,勾配降下法によって最適化されるニューラルネットのパラメータの外にあるパラメータのことであり,具体的にはモデルの層の幅・深さなどネットワークのアーキテクチャに関わるもの,学習率やモメンタムなどパラメータの更新則に関わるものなどが含まる. 深層学習においてハイパーパラメータの調整はとても重要なタスクである. しかしながら,ハイパーパラメータを調整するには,少しずつ条件を変えながら何度もニューラルネットを学習させる必要があり,多くの計算時間がかかる. 研究・開発においては,スループットよくたくさんのモデルの可能性を探索することが生産性を決める重要なファクターであり,ハイパーパラメータ探索を高速に解くという問題は極めて関心が高い. 本ハンズオンでは,クラウドの強力な計算リソースを利用して並列的にニューラルネットの訓練を実行することで,この問題を解く方法を学んでいこう.

Auto scaling groups (ASG)

ハンズオンに入っていく前に, Auto scaling groups (ASG) とよばれる EC2 の概念を知っておく必要がある.

ECS の概要を示した figure_title を振り返って見てほしい. 前章 (Hands-on #3: AWS で自動質問回答ボットを走らせる) でも説明したが, ECS のクラスターで計算を担う実体としては EC2 と Fargate を指定することができる. Fargate については前章で記述した. Fargate を用いると,自在にスケールする計算環境をとても簡単な設定で構築することができた. しかし, GPU を利用することができないなど,いくつかの制約があった. EC2 を使用した計算環境を指定することで,プログラミングの複雑度は増すが, GPU やその他のより高度かつ複雑な設定を伴ったクラスターを構築することができる.

EC2 クラスターには ASG と呼ばれるサービスが配置される. ASG は複数の EC2 インスタンスをロジカルな単位でグループ化することでクラスターを構成する. ASG はクラスター内に新しいインスタンスを起動する,あるいは不要になったインスタンスを停止するなどのスケーリングを担う. ASG で重要な概念として, desired capacity, minimum capacity, maximum capacity というパラメータがある. minimum capacity, maximum capacity は,それぞれクラスター内に配置できるインスタンスの数の最小値・最大値を指定するパラメータである. 前者は,クラスターに負荷がかかっていない場合でもアイドリング状態にあるインスタンスを維持することで,急に負荷が増大した時などのバッファーとして作用することができる. 後者は,負荷が急に増えたときに,過剰な数のインスタンスが起動する事態を防ぎ,経済的なコストの上限を定める役割を果たす.

desired capacity が,その時々でシステムが要求するインスタンスの数を指定する. desired capacity は,例えば 24 時間のリズムに合わせてインスタンスの数を増減させる (昼は多く夜は少なくなど) などの決まったスケジュールに基づいた設定を適用することができる. あるいはクラスター全体にかかっている負荷に応じて, desired capacity を動的に制御することも可能である. どのような基準でクラスターのスケーリングを行うかを定めるルールのことを,スケーリングポリシーとよぶ. たとえば,クラスター全体の稼働率 (負荷) を常に 80% に維持する,などのスケーリングポリシーが想定できる. この場合,クラスター全体の負荷が 80%を下回ったときにはクラスターからインスタンスが削除され,80%を超える (あるいは超えると予測される) 場合はインスタンスを追加する,という操作が ASG によって自動的に行われる.

上記のようなパラメータを検討し,ユーザーは ASG を作成する. ASG を作成したのち, ECS との連携をプログラムしてあげることで, ECS を介して ASG による EC2 クラスターにタスクを投入することが可能になる.

AWS Batch

AWS Batch のアイコン

先に説明したように, ECS と ASG を組み合わせることで,所望の計算クラスターを構築することが可能である. しかしながら, ECS と ASG にはかなり込み入った設定が必要であり,初心者にとっても経験者にとってもなかなか面倒なプログラミングが要求される. そこで, ECS と ASG によるクラスターの設計を自動化してくれるサービスが提供されている. それが AWS Batch である.

AWS Batch はその名のとおりバッチ (Batch) 化されたジョブ (入力データだけが異なる独立した演算が繰り返し実行されること) を想定している. 多くの科学計算や機械学習がバッチ計算に当てはまる. たとえば,初期値のパラメータを変えて複数のシミュレーションを走らせる,といったケースだ. AWS Batch を用いることの利点は,クラスターのスケーリングやジョブの割り振りはすべて自動で実行され, ユーザーはクラウドの舞台裏の詳細を気にすることなく,大量のジョブを投入できるシステムが手に入る点である. が,知識として背後では ECS/ASG/EC2 の三つ巴が協調して動作しているという点は知っておいてほしい.

AWS Batch では,ジョブの投入・管理をスムーズに行うため,次のような概念が定義されている (figure_title). まず, ジョブ (Job) というのが,AWS Batch によって実行される一つの計算の単位である. Job definitions とはジョブの内容を定義するものであり,これには実行されるべき Docker のイメージのアドレスや,割り当てる CPU・RAM の容量,環境変数などの設定が含まれる. Job definition に基づいて個々のジョブが実行される. ジョブが実行されると,ジョブは Job queues に入る. Job queues とは,実行待ち状態にあるジョブの列のことであり,時間的に最も先頭に投入されたジョブが最初に実行される. また,複数の queue を配置し, queue ごとに priority (優先度) を設定することが可能であり, priority の高い queue に溜まったジョブが優先的に実行される (筆者はこれをディズニーランドの"ファストパス"を連想して捉えている). Compute environment とは,先述したクラスターとほぼ同義の概念であり,計算が実行される場所 (EC2 や Fargate からなるクラスター) を指す. Compute environment には,使用する EC2 のインスタンスタイプや同時に起動するインスタンス数の上限などの簡易なスケーリングポリシーが指定されている. Job queues は Compute environment の空き状況を監視しており, それに応じてジョブを Compute environment に投下する.

以上が AWS Batch を使用するうえで理解しておかなければならない概念であるが,くどくど言葉で説明してもなかなかピンとこないだろう. ここからは,実際に自分で手を動かしながら学んでいこう.

AWS Batch の主要な概念

EC2 or Fargate?

ECS でクラスターを構成する際,計算を実行する場として EC2 と Fargate の二つの選択肢があることを説明した. それぞれ長所と短所を抱えているのだが,どのような場合にどちらを使うべきだろうか? それを検討するため,まずは table_title を見てみよう. これは EC2 と Fargate の特徴をまとめたものである. 説明の都合上,大幅な粗視化が行われている点は留意していただきたい.

EC2 vs Fargate
EC2Fargate

Compute capacity

Medium to large

Small to medium

GPU

Yes

No

Launch speed

Slow

Fast

Task placement flexibility

Low

High

Programming complexity

High

Low

これまでに見てきたように, EC2 は最大の CPU 数・メモリーサイズが大きかったり, GPU を利用できたりするなど,単一のインスタンスでの計算能力は高い. 対して, Fargate は単一インスタンスの最大 CPU 数は 4 コアが上限である. その一方で,インスタンスの起動に要する時間は Fargate のほうが圧倒的に早く,より俊敏にクラスターのスケーリングを行うことができる. また,タスクをクラスターに投入する際のフレキシビリティも Fargate のほうが高い. フレキシビリティというのは,例えば一つのインスタンスで 2 つ以上のコンテナを走らせる,などの状況である. 単位 CPU あたりで処理されるタスクの数を最大化する際には,このような設計がしばしば採用される. プログラミングの複雑さという観点からは, Fargate のほうが一般的にシンプルな実装になる.

このように, EC2 と Fargate は互いに相補的な特性を有しており,アプリケーションによって最適な計算環境は検討される必要がある. また,EC2 と Fargate を両方用いたハイブリッドクラスターというのも定義可能であり,そのような選択肢もしばしば用いられる.

準備

ハンズオンのソースコードは GitHub の handson/aws-batch にある.

本ハンズオンの実行には,第一回ハンズオンで説明した準備 (準備) が整っていることを前提とする. また, Docker が自身のローカルマシンにインストール済みであることも必要である.

このハンズオンは, g4dn.xlarge タイプの EC2 インスタンスを使うので,アメリカ東部 (us-east-1) リージョンでは 0.526 $/hour のコストが発生する. 東京 (ap-northeast-1) を選択した場合は 0.71 $/hour のコストが発生する.

準備 でも注意したが,このハンズオンを始める前に G タイプインスタンスの起動上限を AWS コンソールの EC2 管理画面から確認しよう. もし上限が 0 になっていた場合は,上限緩和の申請を行う必要がある. アプリケーションの説明 にも関連した情報を記載しているので,併せて参照されたい.

MNIST 手書き文字認識 (再訪)

今回のハンズオンでは,機械学習のハイパーパラメータ調整を取り上げると冒頭で述べた. その最もシンプルな例題として, 実践ディープラーニング! MNIST 手書き数字認識タスク で扱った MNIST 手書き文字認識の問題を再度取り上げよう. 実践ディープラーニング! MNIST 手書き数字認識タスク では,適当にチョイスしたハイパーパラメータを用いてモデルの訓練を行った. ここで使用したプログラムのハイパーパラメータとしては,確率的勾配降下法 (SGD) における学習率やモメンタムが含まれる. コードでいうと,次の行が該当する.

python
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)

ここで使用された 学習率 (lr=0.01) やモメンタム (momentum=0.5) は恣意的に選択された値であり,これがベストな数値であるのかはわからない. たまたまこのチョイスが最適であるかもしれないし,もっと高い精度を出すハイパーパラメータの組が存在するかもしれない. この問題に答えるため,ハイパーパラメータサーチを行おう. 今回は,最もシンプルなアプローチとして,グリッドサーチによるハイパーパラメータサーチを行おう.

機械学習のハイパーパラメータの最適化には大きく3つのアプローチが挙げられる. グリッドサーチ,ランダムサーチ,そしてベイズ最適化による方法である.

グリッドサーチとは,ハイパーパラメータの組をある範囲の中で可能な組み合わせをすべて計算し,最適なパラメータの組を見出す方法である. 最もシンプルかつ確実な方法であるが,すべての組み合わせの可能性を愚直に計算するので計算コストが大きい.

ランダムサーチ法とは,ハイパーパラメータの組をある範囲の中でランダムに抽出し,大量に試行されたランダムな組の中から最適なパラメータの組を見出す方法である. すべての可能性を網羅的に探索できるわけではないが,調整すべきパラメータの数が多数ある場合に,グリッドサーチよりも効率的に広い探索空間をカバーすることができる.

ベイズ最適化を用いた方法では,過去の探索結果から次にどの組み合わせを探索すべきかという指標を計算し,次に探索するパラメータを決定する. これにより,理論的にはグリッドサーチやランダムサーチ法よりも少ない試行回数で最適なパラメータにたどり着くことができる.

並列化の観点でいうと,グリッドサーチとランダムサーチは各ハイパーパラメータの組の計算は独立に実行することができるため並列化が容易である. このように独立したジョブとして分割・並列化可能な問題を Embarrassingly parallel な問題とよぶ (直訳すると"恥ずかしいほど並列化可能な問題",ということになる). Embarrassingly parallel な問題はクラウドの強力な計算リソースを用いることで,非常なシンプルな実装で解くことができる. この章ではこのようなタイプの並列計算を取り上げる.

一方,ベイズ最適化による方法は,過去の結果をもとに次の探索が決定されるので,並列化はそれほど単純ではない. 最近では optuna などのハイパーパラメータ探索のためのライブラリが発達しており,ベイズ最適化の数理的な処理を自動で実行してくれるので便利である. これらのライブラリを使うと,もし一台のコンピュータ (ノード) の中に複数の GPU が存在する場合は,並列に計算を実行することができる. しかしながら,一台のノードにとどまらず,複数のノードをまたいだ並列化は,高度なプログラミングテクニックが必要とされるだけでなく,ノード間の接続様式などクラウドのアーキテクチャにも深く依存するものである. 本書ではここまで高度なクラウドの使用方法には立ち入らない.

まずは,本ハンズオンで使用する Docker イメージをローカルで実行してみよう.

Docker イメージのソースコードは handson/aws-batch/docker にある. 基本的に 実践ディープラーニング! MNIST 手書き数字認識タスク のハンズオンを元にし,本ハンズオン専用の軽微な変更が施してある. 興味のある読者はソースコードも含めて読んでいただきたい.

練習として,この Docker イメージを手元でビルドするところからはじめてみよう. Dockerfile が保存されているディレクトリに移動し, mymnist という名前 (Tag) をつけてビルドを実行する.

sh
$ cd handson/aws-batch/docker
$ docker build -t mymnist .
$ cd handson/aws-batch/docker
$ docker build -t mymnist .

docker build でエラーが出たときは次の可能性を疑ってほしい. ビルドの中で, MNIST の画像データセットを http://yann.lecun.com/exdb/mnist/ からダウンロードするのだが,ダウンロード先のサーバーがしばしばダウンしている. 世界中の機械学習ユーザーがアクセスするので,これはしばしば発生するようである. サーバーがダウンしているとビルドも失敗してしまう. エラーメッセージにそれらしい文言が含まれていたら,この可能性を疑おう.

手元でビルドするかわりに, Docker Hub から pull することも可能である. その場合は次のコマンドを実行する.

sh
$ docker pull tomomano/mymnist:latest
$ docker pull tomomano/mymnist:latest

イメージの準備ができたら,次のコマンドでコンテナを起動し, MNIST の学習を実行する..

sh
$ docker run mymnist --lr 0.1 --momentum 0.5 --epochs 10
$ docker run mymnist --lr 0.1 --momentum 0.5 --epochs 10

このコマンドを実行すると,指定したハイパーパラメータ (--lr で与えられる学習率と --momentum で与えられるモメンタム) を使ってニューラルネットの最適化が始まる. 学習を行う最大のエポック数は --epochs パラメータで指定する. Hands-on #2: AWS でディープラーニングを実践 のハンズオンで見たような, Loss の低下がコマンドライン上に出力されるだろう (figure_title).

Docker を実行した際の出力

上に示したコマンドを使うと,計算は CPU を使って実行される. もし,ローカルの計算機に GPU が備わっており, nvidia-docker の設定が済んでいるならば, 次のコマンドにより GPU を使って計算を実行できる.

sh
$ docker run --gpus all mymnist --lr 0.1 --momentum 0.5 --epochs 10
$ docker run --gpus all mymnist --lr 0.1 --momentum 0.5 --epochs 10

このコマンドでは,--gpus all というパラメータが加わった.

CPU/GPU どちらで実行した場合でも,エポックを重ねるにつれて訓練データ (Train データ) の Loss は単調に減少していくのが見て取れるだろう. 一方,検証データ (Validation データ) の Loss および Accuracy は,ある程度まで減少した後,それ以上性能が向上しないことに気がつくだろう. これを実際にプロットしてみると figure_title のようになるはずである.

(左) Train/Validation データそれぞれの Loss のエポックごとの変化. (右) Validation データの Accuracy のエポックごとの変化

これはオーバーフィッティングとよばれる現象で,ニューラルネットが訓練データに過度に最適化され,訓練データの外のデータに対しての精度 (汎化性能) が向上していないことを示している. このような場合の対処法として, Early stopping とよばれるテクニックが知られている. Early stopping とは,検証データの Loss を追跡し,それが減少から増加に転じるエポックで学習をうち止め,そのエポックでのウェイトパラメータを採用する,というものである. 本ハンズオンでも, Early stopping によって訓練の終了を判断し,モデルの性能評価を行っていく.

MNIST 手書き文字データセットでは,訓練データとして 60,000 枚,テストデータとして 10,000 枚の画像が与えられている. 本ハンズオンで使用するコードでは,訓練データのうち 80% の 48,000 枚を訓練データとして使用し,残り 20% の 12,000 枚を検証データとして用いている. 詳しくはソースコードを参照のこと.

アプリケーションの説明

このハンズオンで作成するアプリケーションの概要を figure_title に示す.

アプリケーションのアーキテクチャ

簡単にまとめると,次のような設計である.

  • クライアントは,あるハイパーパラメータの組を指定して Batch にジョブを提出する

  • Batch はジョブを受け取ると, EC2 からなるクラスターで計算を実行する

  • クラスター内では g4dn.xlarge インスタンスが起動する

  • Docker イメージは, AWS 内に用意された ECR (Elastic Container Registry) から取得される

  • 複数のジョブが投下された場合は,その数だけのインスタンスが起動し並列に実行される

  • 各ジョブによる計算の結果は S3 に保存される

  • 最後にクライアントは S3 から結果をダウンロードし,最適なハイパーパラメータの組を決定する

それでは,プログラムのソースコードを見てみよう (handson/aws-batch/app.py).

python
class SimpleBatch(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        bucket = s3.Bucket(
            self, "bucket",
            removal_policy=core.RemovalPolicy.DESTROY,
            auto_delete_objects=True,
        )

        vpc = ec2.Vpc(
            self, "vpc",
            # other parameters...
        )

        #
        managed_env = batch.ComputeEnvironment(
            self, "managed-env",
            compute_resources=batch.ComputeResources(
                vpc=vpc,
                allocation_strategy=batch.AllocationStrategy.BEST_FIT,
                desiredv_cpus=0,
                maxv_cpus=64,
                minv_cpus=0,
                instance_types=[
                    ec2.InstanceType("g4dn.xlarge")
                ],
            ),
            managed=True,
            compute_environment_name=self.stack_name + "compute-env"
        )

        #
        job_queue = batch.JobQueue(
            self, "job-queue",
            compute_environments=[
                batch.JobQueueComputeEnvironment(
                    compute_environment=managed_env,
                    order=100
                )
            ],
            job_queue_name=self.stack_name + "job-queue"
        )

        #
        job_role = iam.Role(
            self, "job-role",
            assumed_by=iam.CompositePrincipal(
                iam.ServicePrincipal("ecs-tasks.amazonaws.com")
            )
        )
        # allow read and write access to S3 bucket
        bucket.grant_read_write(job_role)

        #
        repo = ecr.Repository(
            self, "repository",
            removal_policy=core.RemovalPolicy.DESTROY,
        )

        #
        job_def = batch.JobDefinition(
            self, "job-definition",
            container=batch.JobDefinitionContainer(
                image=ecs.ContainerImage.from_ecr_repository(repo),
                command=["python3", "main.py"],
                vcpus=4,
                gpu_count=1,
                memory_limit_mib=12000,
                job_role=job_role,
                environment={
                    "BUCKET_NAME": bucket.bucket_name
                }
            ),
            job_definition_name=self.stack_name + "job-definition",
            timeout=core.Duration.hours(2),
        )
class SimpleBatch(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        bucket = s3.Bucket(
            self, "bucket",
            removal_policy=core.RemovalPolicy.DESTROY,
            auto_delete_objects=True,
        )

        vpc = ec2.Vpc(
            self, "vpc",
            # other parameters...
        )

        #
        managed_env = batch.ComputeEnvironment(
            self, "managed-env",
            compute_resources=batch.ComputeResources(
                vpc=vpc,
                allocation_strategy=batch.AllocationStrategy.BEST_FIT,
                desiredv_cpus=0,
                maxv_cpus=64,
                minv_cpus=0,
                instance_types=[
                    ec2.InstanceType("g4dn.xlarge")
                ],
            ),
            managed=True,
            compute_environment_name=self.stack_name + "compute-env"
        )

        #
        job_queue = batch.JobQueue(
            self, "job-queue",
            compute_environments=[
                batch.JobQueueComputeEnvironment(
                    compute_environment=managed_env,
                    order=100
                )
            ],
            job_queue_name=self.stack_name + "job-queue"
        )

        #
        job_role = iam.Role(
            self, "job-role",
            assumed_by=iam.CompositePrincipal(
                iam.ServicePrincipal("ecs-tasks.amazonaws.com")
            )
        )
        # allow read and write access to S3 bucket
        bucket.grant_read_write(job_role)

        #
        repo = ecr.Repository(
            self, "repository",
            removal_policy=core.RemovalPolicy.DESTROY,
        )

        #
        job_def = batch.JobDefinition(
            self, "job-definition",
            container=batch.JobDefinitionContainer(
                image=ecs.ContainerImage.from_ecr_repository(repo),
                command=["python3", "main.py"],
                vcpus=4,
                gpu_count=1,
                memory_limit_mib=12000,
                job_role=job_role,
                environment={
                    "BUCKET_NAME": bucket.bucket_name
                }
            ),
            job_definition_name=self.stack_name + "job-definition",
            timeout=core.Duration.hours(2),
        )
  • で,計算結果を保存するための S3 バケットを用意している

  • で, Compute environment を定義している. ここでは g4dn.xlarge のインスタンスタイプを使用するとし,最大の vCPU 使用数は 64 と指定している. また,最小の vCPU は 0 である. 今回は,負荷がかかっていないときにアイドリング状態にあるインスタンスを用意する利点は全くないので,ここは 0 にするのが望ましい.

  • で, <2> で作成した Compute environment と紐付いた Job queue を定義している.

  • で,ジョブが計算結果を S3 に書き込むことができるよう, IAM ロールを定義している. (IAM とはリソースがもつ権限を管理する仕組みである.詳しくは AWS における権限の管理 (IAM) を参照)

  • では, Docker image を配置するための ECR を定義している.

  • で Job definition を作成している. ここでは,4 vCPU, 12000 MB (=12GB) の RAM を使用するように指定している. また,今後必要となる環境変数 (BUCKET_NAME) を設定している. さらに, <4> で作った IAM を付与している.

g4dn.xlarge は 1 台あたり 4 vCPU が割り当てられている. このプログラムでは Compute environment の maximum vCPUs を 64 と指定しているので,最大で 16 台のインスタンスが同時に起動することになる. ここで maxium vCPUs を 64 に限定しているのは,なんらかのミスで意図せぬジョブを大量にクラスターに投入してしまった事態で,高額の AWS 利用料金が発生するのを防ぐためである. もし,自分のアプリケーションで必要と判断したならば自己責任において 64 よりも大きな数を設定して構わない.

ここで注意が一点ある. AWS では各アカウントごとに EC2 で起動できるインスタンスの上限が設定されている. この上限は AWS コンソールにログインし, EC2 コンソールの左側メニューバーの Limits をクリックすることで確認できる (figure_title). g4dn.xlarge (EC2 の区分でいうと G ファミリーに属する) の制限を確認するには, Running On-Demand All G instances という名前の項目を見る. ここにある数字が, AWS によって課されたアカウントの上限であり,この上限を超えたインスタンスを起動することはできない. もし,自分の用途に対して上限が低すぎる場合は,上限の緩和申請を行うことができる. 詳しくは 公式ドキュメンテーション "Amazon EC2 service quotas" を参照のこと.

EC2コンソールから各種の上限を確認する

スタックのデプロイ

スタックの中身が理解できたところで,早速スタックをデプロイしてみよう.

デプロイの手順は,これまでのハンズオンとほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). シークレットキーの設定も忘れずに (AWS CLI のインストール).

sh
# プロジェクトのディレクトリに移動
$ cd handson/aws-batch

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd handson/aws-batch

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイのコマンドが無事に実行されたことが確認できたら,AWS コンソールにログインして,デプロイされたスタックを確認してみよう. コンソールの検索バーで batch と入力し, AWS Batch の管理画面を開く (figure_title).

AWS Batch のコンソール画面 (ダッシュボード)

まず目を向けてほしいのが,画面の一番下にある Compute environment overview の中の SimpleBatchcompute-env という名前の項目だ. Compute environment とは,先ほど述べたとおり,計算が実行される環境 (クラスターと読み替えてもよい) である. プログラムで指定したとおり, g4dn.xlarge が実際に使用されるインスタンスタイプとして表示されている. また, Minimum vCPUs が 0,Maximum vCPUs が 64 と設定されていることも見て取れる. 加えて,この時点では一つもジョブが走っていないので, Desired vCPUs は 0 になっている. より詳細な Compute environment の情報を閲覧したい場合は,名前をクリックすることで詳細画面が開く.

次に,Job queue overview にある SimpleBatch-queue という項目に注目してほしい. ここでは実行待ちのジョブ・実行中のジョブ・実行が完了したジョブを一覧で確認することができる. PENDING, RUNNING, SUCCEEDED, FAILED などのカラムがあることが確認できる.ジョブが進行するにつれて,ジョブの状態がこのカラムにしたがって遷移していく. 後でジョブを実際にサブミットしたときに戻ってこよう.

最後に,今回作成した Job definition を確認しよう. 左側のメニューから Job definitions を選択し,次の画面で SimpleBatchjob-definition という項目を見つけて開く. ここから Job definition の詳細を閲覧することができる (figure_title). 中でも重要な情報としては, vCPUs, Memory, GPU がそれぞれ Docker に割り当てられる vCPU・メモリー・ GPU の量を規定している. また, Image と書いてあるところに,ジョブで使用される Docker イメージが指定されている. ここでは, ECR のレポジトリを参照している. 現時点ではこの ECR は空である. 次のステップとして,この ECR にイメージを配置する作業を行おう.

AWS Batch から Job definition を確認

Docker image を ECR に配置する

さて, Batch がジョブを実行するには,どこか指定された場所から Docker イメージをダウンロード (pull) してくる必要がある. 前回のハンズオン (Hands-on #3: AWS で自動質問回答ボットを走らせる) では,公開設定にしてある Docker Hub からイメージを pull してきた. 今回のハンズオンでは, AWS から提供されているレジストリである ECR (Elastic Container Registry) に image を配置するという設計を採用する. ECR を利用する利点は,自分だけがアクセスすることのできるプライベートなイメージの置き場所を用意できる点である. Batch は ECR からイメージを pull してくることで,タスクを実行する (figure_title).

スタックのソースコードでいうと,次の箇所が ECR を定義している.

python
#
repo = ecr.Repository(
    self, "repository",
    removal_policy=core.RemovalPolicy.DESTROY,
)

job_def = batch.JobDefinition(
    self, "job-definition",
    container=batch.JobDefinitionContainer(
        image=ecs.ContainerImage.from_ecr_repository(repo), #
        ...
    ),
    ...
)
#
repo = ecr.Repository(
    self, "repository",
    removal_policy=core.RemovalPolicy.DESTROY,
)

job_def = batch.JobDefinition(
    self, "job-definition",
    container=batch.JobDefinitionContainer(
        image=ecs.ContainerImage.from_ecr_repository(repo), #
        ...
    ),
    ...
)
  • で,新規の ECR を作成している.

  • で Job definition を定義する中で,イメージを <1> で作った ECR から取得するように指定している. これと同時に, Job definition には ECR へのアクセス権限が IAM を通じて自動的に付与される.

さて,スタックをデプロイした時点では, ECR は空っぽである. ここに自分のアプリケーションで使う Docker イメージを push してあげる必要がある.

そのために,まずは AWS コンソールから ECR の画面を開こう (検索バーに Elastic Container Registry と入力すると出てくる). Private というタブを選択すると, simplebatch-repositoryXXXXXX という名前のレポジトリが見つかるだろう (figure_title).

ECR のコンソール画面

次に,このレポジトリの名前をクリックするとレポジトリの詳細画面に遷移する. そうしたら,画面右上にある View push commands というボタンをクリックする. すると figure_title のようなポップアップ画面が立ち上がる.

ECR への push コマンド

このポップアップ画面で表示されている四つのコマンドを順番に実行していくことで,手元の Docker イメージを ECR に push することができる. push を実行する前に, AWS の認証情報が設定されていることを確認しよう. そのうえで,ハンズオンのソースコードの中にある docker/ という名前のディレクトリに移動する. そうしたら,ポップアップ画面で表示されたコマンドを上から順に実行していく.

ポップアップで表示されるコマンドの 2 つめを見てみると docker build -t XXXXX . となっている. 最後の . が重要で,これは 現在のディレクトリにある Dockerfile を使ってイメージをビルドせよ という意味である. このような理由で, Dockerfile が置いてあるディレクトリに移動する必要がある.

四つ目のコマンドは,数 GB あるイメージを ECR にアップロードするので少し時間がかかるかもしれないが,これが完了するとめでたくイメージが ECR に配置されたことになる. もう一度 ECR のコンソールを見てみると,確かにイメージが配置されていることが確認できる (figure_title). これで,AWS Batch を使ってジョブを実行させるための最後の準備が完了した.

ECR へ image の配置が完了した

単一のジョブを実行する

さて,ここからは実際に AWS Batch にジョブを投入する方法を見ていこう.

ハンズオンのディレクトリの notebook/ というディレクトリの中に, run_single.ipynb というファイルが見つかるはずである (.ipynb は Jupyter notebook のファイル形式). これを Jupyter notebook から開こう.

今回のハンズオンでは, venv による仮想環境の中に Jupyter notebook もインストール済みである. なので,ローカルマシンから以下のコマンドで Jupyter notebook を立ち上げる.

sh
# .env の仮想環境にいることを確認
(.env) $ cd notebook
(.env) $ jupyter notebook
# .env の仮想環境にいることを確認
(.env) $ cd notebook
(.env) $ jupyter notebook

Jupyter notebook が起動したら, run_single.ipynb を開く.

最初の [1], [2], [3] 番のセルは,ジョブをサブミットするための関数 (submit_job()) を定義している.

python
# [1]
import boto3
import argparse

# [2]
# AWS 認証ヘルパー ...省略...

# [3]
def submit_job(lr:float, momentum:float, epochs:int, profile_name="default"):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    client = session.client("batch")

    title = "lr" + str(lr).replace(".", "") + "_m" + str(momentum).replace(".", "")
    resp = client.submit_job(
        jobName=title,
        jobQueue="SimpleBatchjob-queue",
        jobDefinition="SimpleBatchjob-definition",
        containerOverrides={
            "command": ["--lr", str(lr),
                        "--momentum", str(momentum),
                        "--epochs", str(epochs),
                        "--uploadS3", "true"]
        }
    )
    print("Job submitted!")
    print("job name", resp["jobName"], "job ID", resp["jobId"])
# [1]
import boto3
import argparse

# [2]
# AWS 認証ヘルパー ...省略...

# [3]
def submit_job(lr:float, momentum:float, epochs:int, profile_name="default"):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    client = session.client("batch")

    title = "lr" + str(lr).replace(".", "") + "_m" + str(momentum).replace(".", "")
    resp = client.submit_job(
        jobName=title,
        jobQueue="SimpleBatchjob-queue",
        jobDefinition="SimpleBatchjob-definition",
        containerOverrides={
            "command": ["--lr", str(lr),
                        "--momentum", str(momentum),
                        "--epochs", str(epochs),
                        "--uploadS3", "true"]
        }
    )
    print("Job submitted!")
    print("job name", resp["jobName"], "job ID", resp["jobId"])

submit_job() 関数について簡単に説明しよう. MNIST 手書き文字認識 (再訪) で, MNIST の Docker をローカルで実行したとき,次のようなコマンドを使用した.

sh
$ docker run -it mymnist --lr 0.1 --momentum 0.5 --epochs 10
$ docker run -it mymnist --lr 0.1 --momentum 0.5 --epochs 10

ここで, --lr 0.1 --momentum 0.5 --epochs 10 の部分が,コンテナに渡されるコマンドである.

AWS Batch でジョブを実行する際も,ContainerOverridescommand というパラメータを使用することで,コンテナに渡されるコマンドを指定することができる. コードでは以下の部分が該当する.

python
containerOverrides={
    "command": ["--lr", str(lr),
                "--momentum", str(momentum),
                "--epochs", str(epochs),
                "--uploadS3", "true"]
}
containerOverrides={
    "command": ["--lr", str(lr),
                "--momentum", str(momentum),
                "--epochs", str(epochs),
                "--uploadS3", "true"]
}

続いて, [4] 番のセルに移ろう. ここでは,上記の submit_job() 関数を用いて, 学習率 = 0.01, モメンタム=0.1, エポック数=100 を指定したジョブを投入する.

python
# [4]
submit_job(0.01, 0.1, 100)
# [4]
submit_job(0.01, 0.1, 100)

AWS の認証情報は, Jupyter Notebook の内部から再度定義する必要がある. これを手助けするため, Notebook の [2] 番のセル (デフォルトではすべてコメントアウトされている) を用意した. これを使うにはコメントアウトを解除すればよい. このセルを実行すると, AWS の認証情報を入力する対話的なプロンプトが表示される. プロンプトに従って aws secret key などを入力することで, (Jupyter のセッションに固有な) 環境変数に AWS の認証情報が記録される.

もう一つの認証方法として, submit_job() 関数に profile_name というパラメータを用意した. もし ~/.aws/credentials に認証情報が書き込まれているのならば (詳しくは AWS CLI のインストール), profile_name に使用したいプロファイルの名前を渡すだけで, 認証を行うことができる. 慣れている読者は後者のほうが便利であると感じるだろう.

[4] 番のセルを実行したら,ジョブが実際に投入されたかどうかを AWS コンソールから確認してみよう. AWS Batch の管理コンソールを開くと, figure_title のような画面が表示されるだろう.

AWS Batch でジョブが実行されている様子

figure_title で赤で囲った箇所に注目してほしい. 一つのジョブが投入されると,それは SUBMITTED という状態を経て RUNNABLE という状態に遷移する. RUNNABLE とは, ジョブを実行するためのインスタンスが Compute environment に不足しているため,新たなインスタンスが起動されるのを待っている状態に相当する. インスタンスの準備が整うと,ジョブの状態は STARTING を経て RUNNING に至る.

次に,ジョブのステータスが RUNNING のときの Compute environment の Desired vCPU を見てみよう (figure_title で紫で囲った箇所). ここで 4 と表示されているのは, g4dn.xlarge インスタンス一つ分の vCPU の数である. ジョブの投入に応じて,それを実行するのに最低限必要な EC2 インスタンスが起動されたことが確認できる (興味のある人は, EC2 コンソールも同時に覗いてみるとよい).

しばらく経つと,ジョブの状態は RUNNING から SUCCEEDED (あるいは何らかの理由でエラーが発生したときには FAILED) に遷移する. 今回のハンズオンで使っている MNIST の学習はだいたい 10 分くらいで完了するはずである. ジョブの状態が SUCCEEDED になるまで見届けよう.

ジョブが完了すると,学習の結果 (エポックごとの Loss と Accuracy を記録した CSV ファイル) は S3 に保存される. AWS コンソールからこれを確認しよう.

S3 のコンソールに行くと simplebatch-bucketXXXX (XXXX の部分はユーザーによって異なる) という名前のバケットが見つかるはずである. これをクリックして中身を見てみると, metrics_lr0.0100_m0.1000.csv という名前の CSV があることが確認できるだろう (figure_title). これが, 学習率 = 0.01, モメンタム = 0.1 として学習を行ったときの結果である.

ジョブの実行結果は S3 に保存される

さて,ここで run_single.ipynb に戻ってこよう. [5] から [7] 番のセルでは,学習結果の CSV ファイルのダウンロードを行っている.

python
# [5]
import pandas as pd
import io
from matplotlib import pyplot as plt

# [6]
def read_table_from_s3(bucket_name, key, profile_name=None):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    s3 = session.resource("s3")
    bucket = s3.Bucket(bucket_name)

    obj = bucket.Object(key).get().get("Body")
    df = pd.read_csv(obj)

    return df

# [7]
bucket_name = "simplebatch-bucket43879c71-mbqaltx441fu"
df = read_table_from_s3(
    bucket_name,
    "metrics_lr0.0100_m0.1000.csv"
)
# [5]
import pandas as pd
import io
from matplotlib import pyplot as plt

# [6]
def read_table_from_s3(bucket_name, key, profile_name=None):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    s3 = session.resource("s3")
    bucket = s3.Bucket(bucket_name)

    obj = bucket.Object(key).get().get("Body")
    df = pd.read_csv(obj)

    return df

# [7]
bucket_name = "simplebatch-bucket43879c71-mbqaltx441fu"
df = read_table_from_s3(
    bucket_name,
    "metrics_lr0.0100_m0.1000.csv"
)

[6] で S3 から CSV データをダウンロードし, pandas の DataFrame オブジェクトとしてロードする関数を定義している. [7] を実行する際, bucket_name という変数の値を,自分自身のバケットの名前に置き換えることに注意しよう (先ほど S3 コンソールから確認した simplebatch-bucketXXXX のことである).

続いて, [9] 番のセルで, CSV のデータをプロットしている (figure_title). ローカルで実行したときと同じように, AWS Batch を用いて MNIST モデルを訓練することに成功した!

python
# [9]
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(9,4))
x = [i for i in range(df.shape[0])]
ax1.plot(x, df["train_loss"], label="Train")
ax1.plot(x, df["val_loss"], label="Val")
ax2.plot(x, df["val_accuracy"])

ax1.set_xlabel("Epochs")
ax1.set_ylabel("Loss")
ax1.legend()

ax2.set_xlabel("Epochs")
ax2.set_ylabel("Accuracy")

print("Best loss:", df["val_loss"].min())
print("Best loss epoch:", df["val_loss"].argmin())
print("Best accuracy:", df["val_accuracy"].max())
print("Best accuracy epoch:", df["val_accuracy"].argmax())
# [9]
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(9,4))
x = [i for i in range(df.shape[0])]
ax1.plot(x, df["train_loss"], label="Train")
ax1.plot(x, df["val_loss"], label="Val")
ax2.plot(x, df["val_accuracy"])

ax1.set_xlabel("Epochs")
ax1.set_ylabel("Loss")
ax1.legend()

ax2.set_xlabel("Epochs")
ax2.set_ylabel("Accuracy")

print("Best loss:", df["val_loss"].min())
print("Best loss epoch:", df["val_loss"].argmin())
print("Best accuracy:", df["val_accuracy"].max())
print("Best accuracy epoch:", df["val_accuracy"].argmax())

AWS Batch で行った MNIST モデルの学習の結果

並列に複数の Job を実行する

さて,ここからが最後の仕上げである. ここまでのハンズオンで構築した AWS Batch のシステムを使って,ハイパーパラメータサーチを実際に行おう.

先ほど実行した run_single.ipynb と同じディレクトリにある run_sweep.ipynb を開く.

セル [1], [2], [3] は run_single.ipynb と同一である.

python
# [1]
import boto3
import argparse

# [2]
# AWS 認証ヘルパー ...省略...

# [3]
def submit_job(lr:float, momentum:float, epochs:int, profile_name=None):
    # ...省略...
# [1]
import boto3
import argparse

# [2]
# AWS 認証ヘルパー ...省略...

# [3]
def submit_job(lr:float, momentum:float, epochs:int, profile_name=None):
    # ...省略...

セル [4] の for ループを使って,グリッド状にハイパーパラメータの組み合わせを用意し, batch にジョブを投入している. ここでは 3x3=9 個のジョブを作成した.

python
# [4]
for lr in [0.1, 0.01, 0.001]:
    for m in [0.5, 0.1, 0.05]:
        submit_job(lr, m, 100)
# [4]
for lr in [0.1, 0.01, 0.001]:
    for m in [0.5, 0.1, 0.05]:
        submit_job(lr, m, 100)

セル [4] を実行したら, Batch のコンソールを開こう. 先ほどと同様に,ジョブのステータスは SUBMITTED > RUNNABLE > STARTING > RUNNING と移り変わっていくことがわかるだろう. 最終的に 9 個のジョブがすべて RUNNING の状態になることを確認しよう (figure_title). また,このとき Compute environment の Desired vCPUs は 4x9=36 となっていることを確認しよう (figure_title).

複数のジョブを同時投入したときの Batch コンソール

次に,Batch のコンソールの左側のメニューから Jobs をクリックしてみよう. ここでは,実行中のジョブの一覧が確認することができる (figure_title). ジョブのステータスでフィルタリングをすることも可能である. 9 個のジョブがどれも RUNNING 状態にあることが確認できるだろう.

複数のジョブを同時投入したときの Job 一覧

今度は EC2 コンソールを見てみよう. 左のメニューから Instances を選択すると, figure_title に示すような起動中のインスタンスの一覧が表示される. g4dn.xlarge が 9 台稼働しているのが確認できる. Batch がジョブの投下に合わせて必要な数のインスタンスを起動してくれたのだ!

複数のジョブを同時投入したときの EC2 インスタンスの一覧

ここまで確認できたら,それぞれの Job が終了するまでしばらく待とう (だいたい 10-15 分くらいで終わる). すべてのジョブが終了すると,ダッシュボードの SUCCEEDED が 9 となっているはずだ. また, Compute environment の Desired vCPUs も 0 に落ちていることを確認しよう. 最後に EC2 コンソールに行って,すべての g4dn インスタンスが停止していることを確認しよう.

以上から, AWS Batch を使うことで,ジョブの投入に応じて自動的に EC2 インスタンスが起動され,ジョブの完了とともに,ただちにインスタンスの停止が行われる一連の挙動を観察することができた. 一つのジョブの完了におよそ 10 分の時間がかかるので,9 個のハイパーパラメータの組を逐次的に計算していた場合は 90 分の時間を要することになる. AWS Batch を使ってこれらの計算を並列に実行することで,ジョブ一個分の計算時間 (=10 分) ですべての計算を終えることができた!

さて,再び run_sweep.ipynb に戻ってこよう. [5] 以降のセルでは,グリッドサーチの結果を可視化している.

python
# [5]
import pandas as pd
import numpy as np
import io
from matplotlib import pyplot as plt

# [6]
def read_table_from_s3(bucket_name, key, profile_name=None):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    s3 = session.resource("s3")
    bucket = s3.Bucket(bucket_name)

    obj = bucket.Object(key).get().get("Body")
    df = pd.read_csv(obj)

    return df

# [7]
grid = np.zeros((3,3))
for (i, lr) in enumerate([0.1, 0.01, 0.001]):
    for (j, m) in enumerate([0.5, 0.1, 0.05]):
        key = f"metrics_lr{lr:0.4f}_m{m:0.4f}.csv"
        df = read_table_from_s3("simplebatch-bucket43879c71-mbqaltx441fu", key)
        grid[i,j] = df["val_accuracy"].max()

# [8]
fig, ax = plt.subplots(figsize=(6,6))
ax.set_aspect('equal')

c = ax.pcolor(grid, edgecolors='w', linewidths=2)

for i in range(3):
    for j in range(3):
        text = ax.text(j+0.5, i+0.5, f"{grid[i, j]:0.1f}",
                       ha="center", va="center", color="w")
# [5]
import pandas as pd
import numpy as np
import io
from matplotlib import pyplot as plt

# [6]
def read_table_from_s3(bucket_name, key, profile_name=None):
    if profile_name is None:
        session = boto3.Session()
    else:
        session = boto3.Session(profile_name=profile_name)
    s3 = session.resource("s3")
    bucket = s3.Bucket(bucket_name)

    obj = bucket.Object(key).get().get("Body")
    df = pd.read_csv(obj)

    return df

# [7]
grid = np.zeros((3,3))
for (i, lr) in enumerate([0.1, 0.01, 0.001]):
    for (j, m) in enumerate([0.5, 0.1, 0.05]):
        key = f"metrics_lr{lr:0.4f}_m{m:0.4f}.csv"
        df = read_table_from_s3("simplebatch-bucket43879c71-mbqaltx441fu", key)
        grid[i,j] = df["val_accuracy"].max()

# [8]
fig, ax = plt.subplots(figsize=(6,6))
ax.set_aspect('equal')

c = ax.pcolor(grid, edgecolors='w', linewidths=2)

for i in range(3):
    for j in range(3):
        text = ax.text(j+0.5, i+0.5, f"{grid[i, j]:0.1f}",
                       ha="center", va="center", color="w")

最終的に出力されるプロットが figure_title である.

ハイパーパラメータのグリッドサーチの結果

このプロットから,差は僅かであるが,学習率が 0.1 のときに精度は最大となることがわかる. また,学習率 0.1 のときはモメンタムを変えても大きな差は生じないことが見て取れる.

今回のパラメータサーチは勉強用に極めて単純化されたものである点は承知いただきたい.

たとえば,今回は学習率が 0.1 が最も良いとされたが,それは訓練のエポックを 100 に限定しているからかもしれない. 学習率が低いとその分訓練に必要なエポック数も多くなる. 訓練のエポック数をもっと増やせばまた違った結果が観察される可能性はある.

また,今回は MNIST の訓練データ 60,000 枚のうち, 48,000 枚を訓練データ,残り 12,000 枚を検証データとして用いた. この分割は乱数を固定してランダムに行ったが,もしこの分割によるデータのバイアスを気にするならば, k 個の異なる学習・検証データの分割をあらかじめ用意して,複数回モデルの評価を行う (k-fold cross-validation) 方法も,より精緻なアプローチとして考えられる.

以上のようにして, CNN を用いた MNIST 分類モデルのハイパーパラメータの最適化の一連の流れを体験した. AWS Batch を利用することで,比較的少ないプログラミングで,動的に EC2 クラスターを制御し,並列にジョブを処理するシステムが構築できた. ここまで EC2 を使いこなすことができれば,多くの問題を自力で解くことが可能になるだろう!

スタックの削除

これにて,本ハンズオンは終了である.最後にスタックを削除しよう. 今回のスタックを削除するにあたり,ECR に配置された Docker のイメージは手動で削除されなければならない (これをしないと, cdk destroy を実行したときにエラーになってしまう. これは CloudFormation の仕様なので従うしかない).

ECR の Docker image を削除するには, ECR のコンソールに行き,イメージが配置されたレポジトリを開く. そして,画面右上の DELETE ボタンを押して削除する (figure_title).

ECR から Docker image を削除する

あるいは, AWS CLI から同様の操作を行うには,以下のコマンドを用いる (XXXX は自分の ECR レポジトリ名に置き換える).

sh
$ aws ecr batch-delete-image --repository-name XXXX --image-ids imageTag=latest
$ aws ecr batch-delete-image --repository-name XXXX --image-ids imageTag=latest

image の削除が完了したうえで,次のコマンドでスタックを削除する.

sh
$ cdk destroy
$ cdk destroy

(#sec:batch_development_and_debug) === クラウドを用いた機械学習アプリケーションの開発とデバッグ

本章で紹介したハンズオンでは, AWS Batch を使用することでニューラルネットの学習を複数並列に実行し,高速化を実現した. 本章の最後の話題として,クラウドを用いた機械学習アプリケーションの開発とデバッグの方法について述べよう.

ローカルに GPU を搭載した強力なマシンがなく,クラウドを利用する予算が確保されているのであれば, figure_title のような開発のスキームが理想的であると考える. 最初の段階では, Hands-on #2: AWS でディープラーニングを実践 で見たような方法で, GPU 搭載型の EC2 インスタンスを作成し, Jupyter Notebook などのインタラクティブな環境で様々なモデルを試し実験を行う. Jupyter である程度アプリケーションが完成してきたタイミングで,作成したアプリケーションを Docker イメージにパッケージングする. そして, EC2 上で docker run を行い,作成したイメージがバグなく動作するか確認を行う. その次に,ハイパーパラメータの最適化などのチューニングを, Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する のハンズオンで学んだ AWS Batch などの計算システムを利用して行う. よい深層学習モデルが完成したら,仕上げに大規模データへの推論処理を行うシステムを Hands-on #3: AWS で自動質問回答ボットを走らせる を参考に構築する.

実際,本書ではこの流れに沿って演習を進めてきた. MNIST タスクを解くモデルを,最初 Jupyter Notebook を使用して実験し,そのコードをほとんどそのまま Docker にパッケージし, AWS Batch を用いてハイパーパラメータサーチを行った. このサイクルを繰り返すことで,クラウドを最大限に活用した機械学習アプリケーションの開発を進めることができる.

クラウドを活用した機械学習アプリケーションの開発フロー

小括

ここまでが,本書第二部の内容である. 第一部に引き続き盛りだくさんの内容であったが,ついてこれたであろうか?

第二部ではまず最初に,深層学習の計算をクラウドで実行するため, GPU 搭載型の EC2 インスタンスの起動について解説した. さらに,ハンズオンでは,クラウドに起動した仮想サーバーを使って MNIST 文字認識タスクを解くニューラルネットを訓練した (Hands-on #2: AWS でディープラーニングを実践).

また,より大規模な機械学習アプリケーションを作るための手段として, Docker と ECS によるクラスターの初歩を説明した (Docker 入門). その応用として,英語で与えられた文章問題への回答を自動で生成するボットをクラウドに展開した (Hands-on #3: AWS で自動質問回答ボットを走らせる). タスクの投入に応じて動的に計算リソースが作成・削除される様子を実際に体験できただろう.

さらに, Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する では AWS Batch を用いてニューラルネットの学習を並列に実行する方法を紹介した. ここで紹介した方法は,ミニマムであるが,計算機システムを大規模化していくためのエッセンスが網羅されている. これらのハンズオン体験から,クラウド技術を応用してどのように現実世界の問題を解いていくのか,なんとなくイメージが伝わっただろうか?

本書の第三部では,さらにレベルアップし,サーバーレスアーキテクチャという最新のクラウドの設計手法について解説する. その応用として,ハンズオンでは簡単な SNS サービスをゼロから実装する. 引き続きクラウドの最先端の世界を楽しんでいこう!

Web サービスの作り方

ここからが,本書第三部の内容になる. これまでのセクションでは,仮想サーバーをクラウド上に起動し,そこで計算を走らせる方法について解説をしてきた. EC2, ECS, Fargate, Batch などを利用して,動的にスケールするクラスターを構成し,並列にタスクを実行するクラウドシステムを実装してきた. 振り返ると,これまで紹介してきた内容は,自分自身が行いたい計算をクラウドを駆使することで実現する,という用途にフォーカスしていたことに気がつくだろう. 一方で,広く一般の人々に使ってもらえるような計算サービス・データベースを提供する,というのもクラウドの重要な役割として挙げられる.

本章から始まる第三部では,前回までとは少し方向性を変え,どのようにしてクラウド上にアプリケーションを展開し,広く一般の人に使ってもらうか,という点を講義したいと思う. これを通じて,どのようにして世の中のウェブサービスができ上がっているのかを知り,さらにどうやって自分でそのようなアプリケーションをゼロから構築するのか,という点を学んでもらう. その過程で,サーバーレスアーキテクチャという最新のクラウド設計手法を解説する.

その前準備として,本章ではどのようにしてウェブサービスが出来上がっているのか,その背後にある技術の概要を解説する. 用語の解説が中心となるが,後のハンズオンを実装するために必須の知識であるので,理解して前に進むよう心がけよう.

ウェブサービスの仕組み  — Twitter を例に

あなたがパソコンやスマートフォンから Twitter, Facebook, YouTube などのウェブサービスにアクセスしたとき,実際にどのようなことが行われ,コンテンツが提示されているのだろうか?

HTTP を通じたサーバーとクライアントのデータのやり取りは,すでに知っている読者も多いだろうし,逆にすべて解説しようとすると紙面が足りないので,ここではエッセンスの説明のみにとどめる. 以降では Twitter を具体例として,背後にあるサーバーとクライアントの間の通信を概説しよう. 概念図としては figure_title のような通信がクライアントとサーバーの間で行われていることになる.

クライアントと Web サーバーの通信の概念図

前提として,クライアントとサーバーの通信は HTTP (Hypertext Transfer Protocol) を使って行われる. また,最近では,暗号化された HTTP である HTTPS (HTTPS (Hypertext Transfer Protocol Secure)) を用いることがスタンダードになってきている. 第一のステップとして,クライアントは HTTP(S) 通信によってサーバーから静的なコンテンツを取得する. 静的なコンテンツとは, HTML (Hyptertext Markup Language) で記述されたウェブページの文書本体, CSS (Cascading Style Sheets) で記述されたページのデザインやレイアウトファイル,そして JavaScript (JS) で記述されたページの動的な挙動を定義したプログラム,が含まれる. Twitter を含む現代的なウェブアプリケーションの設計では,この静的なファイル群はページの”枠”を定義するだけで,中身となるコンテンツ (例: ツイートの一覧) は別途 API (Application Programming Interface) によって取得されなければならない. そこで,クライアントは先のステップで取得された JavaScript で定義されたプログラムに従って,サーバーに API を送信し,ツイートや画像データを取得する. この際,テキストデータのやり取りには JSON (JavaScript Object Notation) というフォーマットが用いられることが多い. 画像や動画などのコンテンツも同様に API により取得される. このようにして取得されたテキストや画像が,HTML の文書に埋め込まれることで,最終的にユーザーに提示されるページが完成するのである. また,新しいツイートを投稿するときにも,クライアントから API を通じてサーバーのデータベースにデータが書き込まれる.

REST API

API (Application Programming Interface) とはこれまで何度も出てきた言葉であるが,ここではよりフォーマルな定義付けを行う. API とはあるソフトウェア・アプリケーションが,外部のソフトウェアに対してコマンドやデータをやり取りするための媒介の一般的総称である. とくに,ウェブサービスの文脈では,サーバーが外界に対して提示しているコマンドの一覧のことを意味する. クライアントは,提示されている API から適切なコマンドを使うことによって,所望のデータを取得したり,あるいはサーバーにデータを送信したりする.

とくに,ウェブの文脈では REST (Representational State Transfer) とよばれる設計思想に基づいた API が現在では最も一般的に使われている. REST の設計指針に従った API のことを REST API あるいは RESTful API とよんだりする.

REST API は, figure_title に示したような MethodURI (Universal Resource Identifier) の組からなる.

REST API

Method (メソッド) とは,どのような操作を行いたいかを抽象的に表す,"動詞" として捉えることができる. メソッドには HTTP 規格で定義された 9 個の動詞 (verb) を使用することができる. この中でも, GET, POST, PUT, PATCH, DELETE の 5 個が最も頻繁に使用される (table_title). この 5 つのメソッドによる操作を総称して CRUD (create, read, update, and delete) とよぶ.

REST API Methods
メソッド意図される動作

GET

要素を取得する

POST

新しい要素を作成する

PUT

既存の要素を新しい要素と置き換える

PATCH

既存の要素の一部を更新する

DELETE

要素を削除する

一方, URI は操作が行われる対象,すなわち "目的語" を表す. ウェブの文脈では操作が行われる対象のことをしばしば リソース とよぶ. URI は多くの場合 http または https から始まるウェブサーバーのアドレスから始まり, / (スラッシュ) 以降に所望のリソースのパスが指定される. figure_title の例で言えば, https://api.twitter.com というアドレスの /1.1/status/home_timeline というリソースを取得 (GET) せよ,という意味になる (なお,ここで 1.1 という数字は API のバージョンを示している). この API リクエストによって,ユーザーのホームのタイムラインのツイートの一覧が取得される.

REST API のメソッドには, table_title で挙げたもの以外に, HTTP プロトコルで定義されているほかのメソッド (OPTIONS, TRACE など) を用いることもできるが,あまり一般的ではない.

また,これらのメソッドだけでは動詞として表現しきれないこともあるが, URI の名前でより意味を明確にすることもある. メソッドの使い方も,要素を削除する際は必ず DELETE を使わなければならない,という決まりもなく,たとえば, Twitter API でツイートを消す API は POST statuses/destroy/:id で定義されている. 最終的には,各ウェブサービスが公開している API ドキュメンテーションを読んで,それぞれの API がどんな操作をするのかを調べる必要がある.

REST の概念は 2000 年代初頭に確立され,今日の API 設計のスタンダードとなった. 一方で,ウェブのテクノロジーが進歩するにつれて,新たな API の設計アプローチの需要も高まっている. 近年とくに人気を集めているのが, GraphQL と呼ばれる API の設計方法である. GraphQL は Facebook 社によって最初に作られ,現在は GraghQL Foundation によって維持と更新がされている. GraphQL を使用すると,クライアントは REST と比較してより柔軟性の高いデータのクエリを行うことができるなど,いくつかの利点がある. キーワードだけでも知っておくと,今後役に立つだろう.

Twitter API

もう少し具体的にウェブサービスの API を体験する目的で,ここでは Twitter の API を見てみよう. Twitter が提供している API の一覧は Twitter の Developer Documentation で見ることができる. いくつかの代表的な API を table_title にまとめた.

Twitter API
エンドポイント動作

GET statuses/home_timeline

ホームのタイムラインのツイートの一覧を取得する.

GET statuses/show/:id

:id で指定されたツイートの詳細情報を取得する.

GET search

ツイートの検索を実行する.

POST statuses/update

新しいツイートを投稿する.

POST media/upload

画像をアップロードする

POST statuses/destroy/:id

:id で指定されたツイートを削除する.

POST statuses/retweet/:id

:id で指定されたツイートをリツイートする.

POST statuses/unretweet/:id

:id で指定されたツイートのリツイートを取り消す.

POST favorites/create

選択したツイートを"いいね"する.

POST favorites/destroy

選択したツイートを"いいね"を取り消す.

この API リストをもとに, Twitter のアプリまたはウェブサイトを開いたときに起こるクライアントとサーバーの通信をシミュレートしてみよう.

ユーザーが Twitter を開くと,まず最初に GET statuses/home_timeline の API リクエストによって,ユーザーのホームのタイムラインのツイートのリストが取得される. 個々のツイートは JSON 形式のデータになっており, id, text, user, coordinates, entities などの属性を含む. id はツイートに固有な ID を表し, text はツイートの本文を含んでいる. user はツイートを投稿したユーザーの名前やプロフィール画像の URL などを含んだ JSON データになっている. coordinates にはツイートが発信された地理的な座標が記録されている. また, entities にはツイートに関連するメディアファイル (画像など) のリンクなどの情報が埋め込まれている. GET statuses/home_timeline からは直近のツイートのリスト (リストが長すぎる場合は途中で切られたもの) が取得される. もしツイートの ID を知っている場合は GET statuses/show/:id を呼ぶことによって, :id パラメータで指定された特定のツイートを取得することができる.

ツイートの検索を行うためには GET search API を使用する. この API には,ツイートに含まれる単語や,ハッシュタグ,ツイートの発信された日時や場所など,様々なクエリの条件を渡すことができる. API からは, GET statuses/home_timeline などと同様, JSON 形式のツイートのデータが返される.

ユーザーが新しいツイートを投稿するには POST statuses/update のエンドポイントを利用する. POST statuses/update には,ツイートの文章や,リプライの場合はリプライ先のツイートの ID などのデータを送信する. また,ツイートに画像データを添付したい場合は, POST media/upload を併せて使用する. ツイートの削除を行うには, POST statuses/destroy/:id を用いる.

そのほか,頻繁に行われる操作としては, POST statuses/retweet/:idPOST statuses/unretweet/:id がある. これらは, :id で指定されるツイートに対して,それぞれリツイートを実行あるいは取り消すための API である. また, POST favorites/createPOST favorites/destroy を使用することによって,選択されたツイートに"いいね"を追加したり,取り消したりする操作を行う.

このような一連の操作が, Twitter のアプリの背後では行われている. また,自分自身でボットを作成したい場合は,これらの API を適切に組み合わせ,カスタムのプログラムを書くことで実現される.

このように, API はあらゆるウェブサービスを作るうえで一番基礎となる要素である. 次からの章では本章で紹介した用語が何度も出てくるので,頭の片隅に置いたうえで読み進めていただきたい.

Serverless architecture

サーバーレスアーキテクチャ (Serverless architecture) あるいは サーバーレスコンピューティング (Serverless computing) とは,従来とは全く異なるアプローチに基づくクラウドシステムの設計方法である. 歴史的には, AWS が 2014 年に発表した Lamba がサーバーレスアーキテクチャの先駆けとされている. その後, Google や Microsoft などのクラウドプラットフォームも同様の機能の提供を開始している. サーバーレスアーキテクチャの利点は,スケーラブルなクラウドシステムを安価かつ簡易に作成できる点であり,近年いたるところで導入が進んでいる.

Serverless とは,文字どおりの意味としてはサーバーなしで計算をするということになるが,それは一体どういう意味だろうか? サーバーレスについて説明するためには,まずは従来的な, "serverful" とよばれるようなシステムについて解説しなければならない.

Serverful クラウド (従来型)

従来的なクラウドシステムのスケッチを figure_title に示す. クライアントから送信されたリクエストは,最初に API サーバーに送られる. API サーバーでは,リクエストの内容に応じてタスクが実行される. タスクには,API サーバーだけで完結できるものもあるが,多くの場合,データベースの読み書きが必要である. データベースには,データベース専用の独立したサーバーマシンが用いられることが一般的である. また,画像や動画などの容量の大きいデータは,また別のストレージサーバーに保存されることが多い. これらの API サーバー,データベースサーバー,ストレージサーバーはそれぞれ独立したサーバーマシンであり, AWS の言葉では EC2 による仮想インスタンスを想定してもらったらよい.

多くのウェブサービスでは,多数のクライアントからのリクエストを処理するため,複数のサーバーマシンがクラウド内で起動し,負荷を分散するような設計がなされている. クライアントから来たリクエストを計算容量に余裕のあるサーバーに振り分けるような操作を Load balancing とよび,そのような操作を担当するマシンのことを Load balancer という.

計算負荷を分散する目的で多数のインスタンスを起動するのはよいのだが,計算負荷が小さすぎてアイドリング状態にあるようではコストと電力の無駄遣いである. したがって,すべてのサーバーが常に目標とする計算負荷を維持するよう,計算の負荷に応じてクラスター内の仮想サーバーの数を動的に増減させるような仕組みが必要である. そのような仕組みをクラスターのスケーリングとよび,負荷の増大に応答して新しい仮想インスタンスをクラスターに追加する操作を scale-out,負荷の減少に応答してインスタンスをシャットダウンする操作を scale-in とよぶ. クラスターのスケーリングは, API サーバーではもちろんのこと,データベースサーバー・ストレージサーバーでも必要になる. ストレージサーバーでは,例えば頻繁にアクセスされるデータはキャッシュ領域に保存したり,データのコピーを複数作るなどのスケーリングが行われる. データベースサーバーも同様に,頻繁にアクセスされるデータのアクセスがパンクしてしまわないよう,分散的な処理が必要となる. このように,クラウドシステム内すべての箇所で,負荷が均一になるような調整が必要であり,開発者は多くの時間をそのチューニングに費やさなければならない. また,サービスの利用者の数などに応じてスケーリングの設定は常に見直される必要があり,継続的な開発が要求される.

さらに問題を複雑にするのは,API サーバーで処理されるべきタスクが,非一様な点である. 非一様であるとは,たとえばタスク A は 3000 ミリ秒の実行時間と 512MB のメモリーを消費し,別のタスク B は 1000 ミリ秒の実行時間と 128MB のメモリーを消費する,というような状況を指している. 一つのサーバーマシンが計算負荷が異なる複数のタスクを処理する場合,クラスターのスケーリングはより複雑になる. この状況をシンプルにするために,1サーバーで実行するタスクは1種類に限る,という設計も可能であるが,そうするとで生まれる弊害も多い (ほとんど使われないタスクに対してもサーバー一台をまるまる割り当てなければならない = ほとんどアイドリング状態になってしまう,など).

Serverful なクラウドシステム

Serverless クラウドへ

Serverful クラウド (従来型) で議論したように,クラスターのスケーリングはクラウドシステムの経済的効率とシステムの安定性を最大化するために必須の作業である. それを反映して,多くの開発者の時間が投資されてきた.

クラスターのスケーリングはすべての開発者が何度も繰り返し行ってきた作業であり,いくつかの側面をテンプレート化し,共通化することができたならば開発のコストを大幅に削減できるだろう. それを実現するには,根本的なレベルからクラウドシステムの設計を考え直す必要がある. スケーリングを前提として考えることで,もっとシンプルで見通しがよいクラウドシステムの設計の仕組みはないだろうか? そのような動機が,サーバーレスアーキテクチャが誕生する背後にあった.

従来の serverful なシステムでの最大の問題点は,サーバーをまるまる占有してしまうという点にある. すなわち, EC2 インスタンスを起動したとき,そのインスタンスは起動したユーザーだけが使えるものであり,計算のリソース (CPU や RAM) が独占的に割り当てられた状態になる. 固定した計算資源の割り当てがされてしまっているので,インスタンスの計算負荷が 0%であろうが 100%であろうが,均一の使用料金が起動時間に比例して発生する.

サーバーレスアーキテクチャは,このような 独占的に割り当てられた計算リソースというものを完全に廃止することを出発点とする. サーバーレスアーキテクチャでは,計算のリソースは,クラウドプロバイダーがすべて管理する. クライアントは,仮想インスタンスを一台まるごと借りるのではなく,計算のタスクの需要が生まれる毎に,実行したいプログラム・コマンドをクラウドに提出する. クラウドプロバイダーは,自身のもつ巨大な計算リソースから空きを探し,提出されたプログラムを実行し,実行結果をクライアントに返す. 言い換えると,計算リソースのスケーリングやアロケーションなどはクラウドプロバイダーが一手に引き受け,ユーザーはジョブをサブミットすることに注力する,という枠組みである. これを図示すると, figure_title のようになる.

従来のクラウドと Serverless クラウドの比較

サーバーレスクラウドでは,スケーリングはすべてクラウドプロバイダーが引き受けるので,スケーラビリティーが保証されている. クライアントが同時に大量のタスクを送信した場合でも,クラウドプロバイダー側の独自の仕組みによってすべてのタスクが遅延なく実行される. また,サーバーレスクラウドを利用することで,クラウドのコストは実際に使用した計算の総量 (稼働時間) で決定されることになる. これは,計算の実行総量に関わらずインスタンスの起動時間で料金が決定されていた従来のシステムと比べて大きな違いである.

サーバーレスクラウドは,従来のクラウドとは根本から異なったアプローチなので,コードの書き方やシステムの設計が大きく異なる. サーバーレスクラウドを開発・運用するには,サーバーレス固有の概念や用語に精通している必要がある. 以降では,実際にクラウドを動かしながら,サーバーレスをより具体的に体験していこう.

従来型の(仮想インスタンスをたくさん起動するような)クラウドシステムは,賃貸と似ているかもしれない. 部屋を借りるというのは,その部屋でどれだけの時間を過ごそうが,月々の家賃は一定である. 同様に,仮想サーバーも,それがどれほどの計算を行っているかに関わらず,一定の料金が時間ごとに発生する.

一方で,サーバーレスクラウドは,電気・水道・ガス料金 と似ている. こちらは,実際に使用した量に比例して料金が決定されている. サーバーレスクラウドも,実際に計算を行った総時間で料金が決まる仕組みになっている.

サーバーレスクラウドを構成するコンポーネント

サーバーレスアーキテクチャの概要がわかってきたところで,ここでは AWS においてサーバーレスクラウドを構成する様々なコンポーネントを紹介していこう. 特に, Lambda, S3, DynamoDB を取り上げ,解説する (figure_title). サーバーレスクラウドは,これらのコンポーネントを統合することで一つのシステムが出来上がる. ここでは, Lambda,S3,DynamoDB を利用する際に押さえておかなければならない知識を一通り説明しきる都合上,具体的なイメージがわきにくいかもしれない. が,続く Hands-on #5: サーバーレス入門 でそれぞれについてハンズオン形式で演習を行うので,そこでさらに理解を深めれば大丈夫である.

Lambda, S3, DynamoDB のアイコン

Lambda

AWS でサーバーレスコンピューティングの中心を担うのが, Lambda である. Lambda の使い方を figure_title に図示している. Lambda の仕組みはシンプルで,まずユーザーは実行したいプログラムのコードを事前に登録しておく. プログラムは, Python, Node.js, Ruby などの主要な言語がサポートされている. Lambda に登録されたひとつひとつのプログラムを関数 (Function) とよぶ. そして,関数を実行したいときに,invoke コマンドを Lambda に送信する. Lambda では, invoke のリクエストを受け取るとただちに (数ミリセカンドから数百ミリセカンド程度の時間で) プログラムの実行を開始する. そして,実行結果をクライアントやその他の計算機に返す.

AWS Lambda

このように,Lambda では占有された仮想インスタンスは存在せず,実行を待っているプログラムだけがある状態である. invoke のリクエストに応じて,プログラムが AWS の巨大な計算機プールのどこかに配置され,実行される. 同時に複数のリクエストが来た場合でも, AWS はそれらを実行するための計算リソースを割り当て,並列的に処理を行ってくれる. 原理上は,数千から数万のリクエストが同時に来たとしても, Lambda はそれらを同時に実行することができる. このような,占有された仮想サーバーの存在なしに,動的に関数を実行するサービスのことを総称して FaaS (Function as a Service) とよぶ.

Lambda ではそれぞれの関数につき, 128MB から 10240MB のメモリーを使用することができる (執筆時点の仕様). また,実効的な CPU のパワーはメモリーの量に比例する形で割り当てられる. すなわち,タスクに割り当てたメモリーの量が多ければ多いほど,より多くの CPU リソースが割り当てられることになる (しかし, RAM と CPU パワーの具体的な換算表は AWS からは公開されていない). 実行時間は 100 ミリ秒の単位で記録され,実行時間に比例して料金が決定される. table_title は Lambda の利用料金表である (執筆時点で ap-north-east1 リージョンを選択した場合).

Lambda の料金表
Memory (MB)Price per 100ms

128

$0.0000002083

512

$0.0000008333

1024

$0.0000016667

3008

$0.0000048958

実行時間に比例する料金に追加して,リクエストを送信するごとに発生する料金が設定されている. これは,百万回のリクエストにつき $0.2 である. たとえば, 128MB のメモリーを使用する関数を,それぞれ 200 ミリ秒,合計で 100 万回実行した場合, 0.0000002083 * 2 * 10^6 + 0.2 = $0.6 の料金となる. ウェブサーバーのデータベースの更新など簡単な計算であれば,200 ミリ秒程度で実行できる関数も多いことから,100 万回データベースの更新を行ったとしても,たった $0.6 しかコストが発生しないことになる. また,コードが実行されず待機状態になっている場合は,発生する料金は 0 である. このように,実際に意味のある処理が行われた時間にのみ,料金が発生する仕組みになっている.

Lambda は比較的短時間で完了する,反復性の高いタスクの実行に向いている. データベースの読み書きはその典型的な例であるが,そのほかにも,画像のサイズをトリミングしたり,サーバーサイドで定期的に実行されるメンテナンス処理などの利用が考えられる. また,複数の Lambda をリレー式に繋げることも可能で,シンプルな処理を組み合わせることで複雑なロジックを表現することができる.

上述の Lambda の料金計算は,説明のためコストに寄与する要素をいくつか省いている点は承知いただきたい. 例えば, DynamoDB の読み書きに関する料金や,ネットワークの通信にかかわるコストが考慮されていない.

サーバーレスストレージ: S3

サーバーレスの概念は,ストレージにも拡張されている.

従来的なストレージ (ファイルシステム) では,必ずホストとなるマシンと OS が存在しなければならない. したがって,それほどパワーは必要ないまでも,ある程度の CPU リソースを割かなければならない. また,従来的なファイルシステムでは,データ領域のサイズは最初にディスクを初期化するときに決めなければならず,後から容量を増加させることはしばしば困難である (ZFS などのファイルシステムを使えばある程度は自由にファイルシステムのサイズを変更することは可能である). よって,従来的なクラウドでは,ストレージを借りる際にはあらかじめディスクのサイズを指定せねばならず,ディスクの中身が空であろうと満杯であろうと,同じ利用料金が発生することになる (figure_title).

Simple Storage Service (S3) は,サーバーレスなストレージシステムを提供する (figure_title). S3 は従来的なストレージシステムと異なり, OS に"マウントする”という概念はない. 基本的に API を通じてデータの読み書きの操作が行われる. また,データの冗長化や暗号化,バックアップの作成など,通常ならば OS と CPU が介在しなければならない操作も, API を通じて行うことができる. S3 では事前に決められたディスク領域のサイズはなく,データを入れれば入れた分だけ,保存領域は拡大していく (仕様上はペタバイトスケールのデータを保存することが可能である). ストレージにかかる料金は,保存してあるデータの総容量で決定される.

S3 と従来的なファイルシステムの比較

S3 を利用する際に,料金に関わってくる主要な事項をまとめたのが table_title である (us-east-1 リージョンのもの. 説明のため主要な事項のみ取り出している. 詳細は 公式ドキュメンテーション "Amazon S3 pricing" を参照).

S3 の利用料金
項目料金

Data storage (First 50TB)

$0.023 per GB per month

PUT, COPY, POST, LIST requests (per 1,000 requests)

$0.005

GET, SELECT, and all other requests (per 1,000 requests)

$0.0004

Data Transfer IN To Amazon S3 From Internet

$0

Data Transfer OUT From Amazon S3 To Internet

$0.09 per GB

第一に,データの保存には $0.025 per GB のコストが月ごとに発生する. したがって,1000GB のデータを S3 に一ヵ月保存した場合, $25 の料金が発生することになる. また,PUT, COPY, POST などのリクエスト (=データを書き込む操作) に対しては,データ容量に関係なく,1000 回ごとに $0.005 のコストが発生する. GET, SELECT などのリクエスト (=データを読み込む操作) に対しては,1000 回ごとに $0.0004 のコストが発生する. また, S3 はデータを外に取り出す際の通信にもコストが生じる. 執筆時点では,S3 からインターネットを通じて外部にデータを転送 (data-out) すると $0.09 per GB のコストが発生する. データをインターネットを通じて S3 に入れる (data-in) 通信は無料で行える. また, AWS の 同じ Region 内のサービス (Lambda や EC2 など) にデータを転送するのは無料である. AWS のリージョンをまたいだデータの転送にはコストが発生する. いずれにせよ,サーバーレスの概念に則り,すべての料金が従量課金制で決定される設定になっている.

サーバーレスデータベース: DynamoDB

サーバーレスの概念は,データベースにも適用することができる.

ここでいうデータベースとは, Web サービスなどにおけるユーザーや商品の情報を記録しておくための保存領域のことを指している. 従来的に有名なデータベースとしては MySQL, PostgreSQL, MongoDB などが挙げられる. データベースと普通のストレージの違いは,データの検索機能にある. 普通のストレージではデータは単純にディスクに書き込まれるだけだが, データベースでは検索がより効率的になるようなデータの配置がされたり, 頻繁にアクセスされるデータはメモリーにキャッシュされるなどの機能が備わっている. これにより,巨大なデータの中から,興味のある要素を高速に取得することができる.

このような検索機能を実現するには,当然 CPU の存在が必須である. したがって,従来的なデータベースを構築する際は,ストレージ領域に加えて,たくさんの CPU コアを搭載したマシンが用いられることが多い. また,データベースが巨大な場合は複数マシンにまたがった分散型のシステムが設計される. 分散型システムの場合は, Serverful クラウド (従来型) で議論したようにデータベースへのアクセス負荷に応じて適切なスケーリングがなされる必要がある.

DynamoDB は, AWS が提供しているサーバーレスな分散型データベースである. サーバーレスであるので,占有されたデータベース用仮想インスタンスは存在せず, API を通じてデータの書き込み・読み出し・検索などの操作を行う. S3 と同様に,データ保存領域の上限は定められておらず,データを入れれば入れた分だけ,保存領域は拡大していく. また,データベースへの負荷が増減したときのスケーリングは, DynamoDB が自動で行うので,ユーザーは心配する必要はない.

DynamoDB での利用料金の計算はやや複雑なのだが, "On-demand Capacity" というモードで使用した場合の料金に関わってくる主要な事項をまとめたのが table_title である (us-east-1 リージョンのもの. 詳細は 公式ドキュメンテーション "Pricing for On-Demand Capacity" を参照).

DynamoDB の利用料金
項目料金

Write request units

$1.25 per million write request units

Read request units

$0.25 per million read request units

Data storage

$0.25 per GB-month

DynamoDB ではデータの書き込み操作の単位を write request unit とよび,データの読み込み操作の単位を read request unit とよぶ. 基本的に, 1kB 以下のデータを一度書き込むと 1 write request unit を消費し,4kB 以下のデータを一度読み込むと 1 read request unit を消費する (詳しくは 公式ドキュメンテーション "Read/Write Capacity Mode" を参照のこと). write request units は 100 万回ごとに $1.25, read request units は 100 万回ごとに $0.25 のコストが設定されている. また,保存されたデータ容量に対して $0.25 per GB のコストが月ごとに発生する. DynamoDB は高速な検索機能などを備えたデータベースであるので, GB あたりのストレージコストは S3 に比べ 10 倍程度高い. DynamoDB のデータの転送に関わるコストは,同じリージョン内ならば data-in,data-out ともに $0 である. リージョンをまたいだ通信には別途コストが発生する.

その他のサーバーレスクラウドの構成要素

以上で紹介した Lambda, S3, DynamoDB がサーバーレスクラウドの中で最も使用する頻度が高いサービスになる. その他のサーバーレスクラウドの構成要素を以下に列挙する. いくつかについては,今後のハンズオンを行う中で改めて解説を行う.

サーバーレスアーキテクチャは万能か?

この問いへの答えは,筆者は NO であると考える.

ここまで,サーバーレスの利点を強調して説明をしてきたが,まだまだ新しい技術なだけに,欠点,あるいはサーバーフルなシステムに劣る点は数多くある.

大きな欠点を一つあげるとすれば,サーバーレスのシステムは各クラウドプラットフォームに固有なものなので,特定のプラットフォームでしか運用できないシステムになってしまう点であろう. AWS で作成したサーバーレスのシステムを, Google のクラウドに移植するには,かなり大掛かりなプログラムの書き換えが必要になる. 一方, serverful なシステムであれば,プラットフォーム間のマイグレーションは比較的簡単に行うことができる. クラウドプロバイダーとしては,自社のシステムへの依存度を強めることで,顧客を離さないようにするという狙いがあるのだろう…

その他,サーバーレスコンピューティングの欠点や今後の課題などは,次の論文で詳しく議論されている. 興味のある読者はぜひ読んでいただきたい.

Hands-on #5: サーバーレス入門

前章ではサーバーレスアーキテクチャの概要の説明を行った. 本章では,ハンズオン形式でサーバーレスクラウドを実際に動かしながら,具体的な使用方法を学んでいこう. 今回のハンズオンでは Lambda, S3, DynamoDB の三つのサーバーレスクラウドの構成要素に触れていく. それぞれについて,短いチュートリアルを用意してある.

Lambda ハンズオン

まずは, Lambda を実際に動かしてみよう. ハンズオンのソースコードは GitHub の handson/serverless/lambda に置いてある.

このハンズオンで使用するアプリケーションのスケッチを figure_title に示す. STEP 1 では,AWS CDK を使用して Python で書かれたコードを Lambda に登録する. 続いて STEP 2 では, Invoke API を使用して,同時にいくつもの Lambda を起動し,並列な計算を行う. Lambda のワークフローを体験する目的で最小限の設定である.

Lambda チュートリアルの概要

このハンズオンは,基本的に AWS Lambda の無料枠 の範囲内で実行することができる.

app.py にデプロイするプログラムが書かれている. 中身を見てみよう.

py
#
FUNC = """
import time
from random import choice, randint
def handler(event, context):
    time.sleep(randint(2,5))
    sushi = ["salmon", "tuna", "squid"]
    message = "Welcome to Cloud Sushi. Your order is " + choice(sushi)
    print(message)
    return message
"""

class SimpleLambda(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        handler = _lambda.Function(
            self, 'LambdaHandler',
            runtime=_lambda.Runtime.PYTHON_3_7,
            code=_lambda.Code.from_inline(FUNC),
            handler="index.handler",
            memory_size=128,
            timeout=core.Duration.seconds(10),
            dead_letter_queue_enabled=True,
        )
#
FUNC = """
import time
from random import choice, randint
def handler(event, context):
    time.sleep(randint(2,5))
    sushi = ["salmon", "tuna", "squid"]
    message = "Welcome to Cloud Sushi. Your order is " + choice(sushi)
    print(message)
    return message
"""

class SimpleLambda(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        handler = _lambda.Function(
            self, 'LambdaHandler',
            runtime=_lambda.Runtime.PYTHON_3_7,
            code=_lambda.Code.from_inline(FUNC),
            handler="index.handler",
            memory_size=128,
            timeout=core.Duration.seconds(10),
            dead_letter_queue_enabled=True,
        )
  • ここで, Lambda で実行されるべき関数を定義している. これは非常に単純な関数で,2-5 秒のランダムな時間スリープした後,["salmon", "tuna", "squid"] のいずれかの文字列をランダムに選択し, "Welcome to Cloud Sushi. Your order is XXXX" (XXXX は選ばれた寿司のネタ) というメッセージをリターンする.

  • 次に, Lambda に <1> で書いた関数を配置している. パラメータの意味は,文字どおりの意味なので難しくはないが,以下に解説する.

    • runtime=_lambda.Runtime.PYTHON_3_7: ここでは, Python3.7 を使って上記で定義された関数を実行せよ,と指定している. Python3.7 のほかに, Node.js, Java, Ruby, Go などの言語を指定することが可能である.

    • code=_lambda.Code.from_inline(FUNC): 実行されるべき関数が書かれたコードを指定する. ここでは, FUNC=... で定義した文字列を渡しているが,文字列以外にもファイルのパスを渡すことも可能である.

    • handler="index.handler": これは,コードの中にいくつかのサブ関数が含まれているときに,メインとサブを区別するためのパラメータである. handler という名前の関数をメイン関数として実行せよ,という意味である.

    • memory_size=128: メモリーは 128MB を最大で使用することを指定している.

    • timeout=core.Duration.seconds(10) タイムアウト時間を 10 秒に設定している. 10 秒以内に関数の実行が終了しなかった場合,エラーが返される.

    • dead_letter_queue_enabled=True: アドバンストな設定なので説明は省略する.

上記のプログラムを実行することで, Lambda 関数がクラウド上に作成される. 早速デプロイしてみよう.

デプロイ

デプロイの手順は,これまでのハンズオンとほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). それぞれの意味を忘れてしまった場合は,ハンズオン 1, 2 に戻って復習していただきたい. シークレットキーの設定も忘れずに (AWS CLI のインストール).

sh
# プロジェクトのディレクトリに移動
$ cd handson/serverless/lambda

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd handson/serverless/lambda

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイのコマンドが無事に実行されれば, figure_title のような出力が得られるはずである. ここで表示されている SimpleLambda.FunctionName = XXXX の XXXX の文字列は後で使うのでメモしておこう.

CDKデプロイ実行後の出力

AWS コンソールにログインして,デプロイされたスタックを確認してみよう. コンソールから,Lambda のページに行くと figure_title のような画面から Lambda の関数の一覧が確認できる.

Lambda コンソール - 関数の一覧

今回のアプリケーションで作成したのが SimpleLambda で始まるランダムな名前のついた関数だ. 関数の名前をクリックして,詳細を見てみる. すると figure_title のような画面が表示されるはずだ. 先ほどプログラムの中で定義した Python の関数がエディターから確認できる. さらに下の方にスクロールすると,関数の各種設定も確認できる.

Lambda コンソール - 関数の詳細

Lambda で実行されるコードは, Lambda のコンソール画面 (figure_title) のエディターで編集することもできる. デバッグをするときなどは,こちらを直接いじる方が早い場合もある. その場合は, CDK のコードに行った編集を反映させなおすことを忘れずに.

Lambda 関数の実行

それでは,作成した Lambda 関数を実行 (invoke) してみよう. AWS の API を使うことで,関数の実行をスタートすることができる. 今回は, handson/serverless/lambda/invoke_one.py に関数を実行するための簡単なプログラムを提供している. 興味のある読者はコードを読んでもらいたい.

以下のコマンドで,Lambda の関数を実行する. コマンドの XXXX の部分は,先ほどデプロイしたときに SimpleLambda.FunctionName = XXXX で得られた XXXX の文字列で置換する.

sh
$ python invoke_one.py XXXX
$ python invoke_one.py XXXX

すると, "Welcome to Cloud Sushi. Your order is salmon" という出力が得られるはずだ. とてもシンプルではあるが,クラウド上で先ほどの関数が走り,乱数が生成されたうえで,ランダムな寿司ネタが選択されて出力が返されている. このコマンドを何度か打ってみて,実行ごとに異なる寿司ネタが返されることを確認しよう.

さて,このコマンドは,一度につき一回の関数を実行したわけであるが, Lambda の本領は一度に大量のタスクを同時に実行できる点である. そこで,今度は一度に 100 個のタスクを同時に送信してみよう. handson/serverless/lambda/invoke_many.py のスクリプトを使用する.

次のコマンドを実行しよう. XXXX の部分は前述と同様に置き換える. 第二引数の 100 は 100 個のタスクを投入せよ,という意味である.

sh
$ python invoke_many.py XXXX 100
$ python invoke_many.py XXXX 100

すると次のような出力が得られるはずだ.

sh
....................................................................................................
Submitted 100 tasks to Lambda!
....................................................................................................
Submitted 100 tasks to Lambda!

実際に,100 個のタスクが同時に実行されていることを確認しよう. figure_title の画面に戻り, "Monitoring" というタブがあるので,それをクリックする. すると, figure_title のようなグラフが表示されるだろう.

Lambda コンソール - 関数の実行のモニタリング

figure_title のグラフの更新には数分かかることがあるので,なにも表示されない場合は少し待つ.

figure_title で "Invocations" が関数が何度実行されたかを意味している. たしかに 100 回実行されていることがわかる. さらに, "Concurrent executions" は何個のタスクが同時に行われたかを示している. ここでは 96 となっていることから,96 個のタスクが並列的に実行されたことを意味している (これが 100 とならないのは,タスクの開始のコマンドが送られたのが完全には同タイミングではないことに起因する).

このように,非常にシンプルではあるが, Lambda を使うことで,同時並列的に処理を実行することのできるクラウドシステムを簡単に作ることができた.

もしこのようなことを従来的な serverful なクラウドで行おうとした場合,クラスターのスケーリングなど多くのコードを書くことに加えて,いろいろなパラメータを調節する必要がある.

興味がある人は,一気に 1000 個などのジョブを投入してみるとよい. Lambda はそのような大量のリクエストにも対応できることが確認できるだろう. が,あまりやりすぎると Lambda の無料利用枠を超えて料金が発生してしまうので注意.

スタックの削除

最後にスタックを削除しよう. スタックを削除するには,次のコマンドを実行すればよい.

sh
$ cdk destroy
$ cdk destroy

DynamoDB ハンズオン

続いて, DynamoDB の簡単なチュートリアルをやってみよう. ハンズオンのソースコードは GitHub の /handson/serverless/dynamodb に置いてある.

このハンズオンで使用するアプリケーションのスケッチを figure_title に示す. STEP 1 では,AWS CDK を使用して DynamoDB のテーブルを初期化し,デプロイする. 続いて STEP 2 では, API を使用してデータベースのデータの書き込み・読み出し・削除などの操作を練習する.

DynamoDB チュートリアルの概要

このハンズオンは,基本的に AWS DynamoDB の無料枠 の範囲内で実行できる.

handson/serverless/dynamodb/app.py にデプロイするプログラムが書かれている. 中身を見てみよう.

python
class SimpleDynamoDb(core.Stack):
    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        table = ddb.Table(
            self, "SimpleTable",
            #
            partition_key=ddb.Attribute(
                name="item_id",
                type=ddb.AttributeType.STRING
            ),
            #
            billing_mode=ddb.BillingMode.PAY_PER_REQUEST,
            #
            removal_policy=core.RemovalPolicy.DESTROY
        )
class SimpleDynamoDb(core.Stack):
    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        table = ddb.Table(
            self, "SimpleTable",
            #
            partition_key=ddb.Attribute(
                name="item_id",
                type=ddb.AttributeType.STRING
            ),
            #
            billing_mode=ddb.BillingMode.PAY_PER_REQUEST,
            #
            removal_policy=core.RemovalPolicy.DESTROY
        )

このコードで,最低限の設定がなされた空の DynamoDB テーブルが作成される. それぞれのパラメータの意味を簡単に解説しよう.

  • partition_key: すべての DynamoDB テーブルには Partition key が定義されていなければならない. Partition key とは,テーブル内の要素 (レコード) ごとに存在する固有の ID のことである. 同一の Partition key をもった要素がテーブルの中に二つ以上存在することはできない (注: Sort Key を使用している場合は除く.詳しくは 公式ドキュメンテーション "Core Components of Amazon DynamoDB" 参照). また, Partition key が定義されていない要素はテーブルの中に存在することはできない. ここでは, Partition key に item_id という名前をつけている.

  • billing_mode: ddb.BillingMode.PAY_PER_REQUEST を指定することで, On-demand Capacity Mode の DynamoDB が作成される. ほかに PROVISIONED というモードがあるが,これはかなり高度なケースを除いて使用しないだろう.

  • removal_policy: CloudFormation のスタックが消去されたときに, DynamoDB も一緒に消去されるかどうかを指定する. このコードでは DESTROY を選んでいるので,すべて消去される. ほかのオプションを選択すると,スタックを消去しても DynamoDB のバックアップを残す,などの動作を定義することができる.

デプロイ

デプロイの手順は,これまでのハンズオンとほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). シークレットキーの設定も忘れずに (AWS CLI のインストール).

sh
# プロジェクトのディレクトリに移動
$ cd handson/serverless/dynamodb

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd handson/serverless/dynamodb

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイのコマンドが無事に実行されれば, figure_title のような出力が得られるはずである. ここで表示されている SimpleDynamoDb.TableName = XXXX の XXXX の文字列は後で使うのでメモしておこう.

CDKデプロイ実行後の出力

AWS コンソールにログインして,デプロイされたスタックを確認してみよう. コンソールから, DynamoDB のページに行き,左のメニューバーから "Tables" を選択する. すると, figure_title のような画面からテーブルの一覧が確認できる.

DynamoDB のコンソール (テーブルの一覧)

今回のアプリケーションで作成したのが SimpleDynamoDb で始まるランダムな名前のついたテーブルだ. テーブルの名前をクリックして,詳細を見てみる. すると figure_title のような画面が表示されるはずだ. "Items" のタブをクリックすると,テーブルの中のレコードを確認できる. 現時点ではなにもデータを書き込んでいないので,空である.

DynamoDB のコンソール (テーブルの詳細画面)

データの読み書き

それでは, デプロイ で作ったテーブルを使ってデータの読み書きを実践してみよう. ここでは Python と boto3 ライブラリを用いた方法を紹介する.

まずは,テーブルに新しい要素を追加してみよう. ハンズオンのディレクトリにある simple_write.py を開いてみよう. 中には次のような関数が書かれている.

python
import boto3
from uuid import uuid4
ddb = boto3.resource('dynamodb')

def write_item(table_name):
    table = ddb.Table(table_name)
    table.put_item(
    Item={
        'item_id': str(uuid4()),
        'first_name': 'John',
        'last_name': 'Doe',
        'age': 25,
        }
    )
import boto3
from uuid import uuid4
ddb = boto3.resource('dynamodb')

def write_item(table_name):
    table = ddb.Table(table_name)
    table.put_item(
    Item={
        'item_id': str(uuid4()),
        'first_name': 'John',
        'last_name': 'Doe',
        'age': 25,
        }
    )

コードを上から読んでいくと,まず最初に boto3 ライブラリをインポートし, dynamodb のリソースを呼び出している. write_item() 関数は, DynamoDB のテーブルの名前 (上で見た SimpleDynamoDb-XXXX) を引数として受け取る. そして, put_item() メソッドを呼ぶことで,新しいアイテムを DB に書き込んでいる. アイテムには item_id, first_name, last_name, age の 4 つの属性が定義されている. ここで, item_id は先ほど説明した Partition key に相当しており, UUID4 を用いたランダムな文字列を割り当てている.

では, simple_write.py を実行してみよう. "XXXX" の部分を自分がデプロイしたテーブルの名前 (SimpleDynamoDb で始まる文字列) に置き換えたうえで,次のコマンドを実行する.

sh
$ python simple_write.py XXXX
$ python simple_write.py XXXX

新しい要素が正しく書き込めたか, AWS コンソールから確認してみよう. figure_title と同じ手順で,テーブルの中身の要素の一覧を表示する. すると figure_title のように,期待通り新しい要素が見つかるだろう.

DynamoDB に新しい要素が追加されたことを確認

boto3 を使ってテーブルから要素を読みだすことも可能である. ハンズオンのディレクトリにある simple_read.py を見てみよう.

python
import boto3
ddb = boto3.resource('dynamodb')

def scan_table(table_name):
    table = ddb.Table(table_name)
    items = table.scan().get("Items")
    print(items)
import boto3
ddb = boto3.resource('dynamodb')

def scan_table(table_name):
    table = ddb.Table(table_name)
    items = table.scan().get("Items")
    print(items)

table.scan().get("Items") によって,テーブルの中にあるすべての要素を読みだしている.

次のコマンドで,このスクリプトを実行してみよう ("XXXX" の部分を正しく置き換えることを忘れずに).

sh
$ python simple_read.py XXXX
$ python simple_read.py XXXX

先ほど書き込んだ要素が出力されることを確認しよう.

大量のデータの読み書き

DynamoDB の利点は,最初に述べたとおり,負荷に応じて自在にその処理能力を拡大できる点である.

そこで,ここでは一度に大量のデータを書き込む場合をシミュレートしてみよう. batch_rw.py に,一度に大量の書き込みを実行するためのプログラムが書いてある.

次のコマンドを実行してみよう (XXXX は自分のテーブルの名前に置き換える).

sh
$ python batch_rw.py XXXX write 1000
$ python batch_rw.py XXXX write 1000

このコマンドを実行することで,ランダムなデータが 1000 個データベースに書き込まれる.

さらに,データベースの検索をかけてみよう. 今回書き込んだデータには age という属性に 1 から 50 のランダムな整数が割り当てられている. age が 2 以下であるような要素だけを検索し拾ってくるには,次のコマンドを実行すればよい.

sh
$ python batch_rw.py XXXX search_under_age 2
$ python batch_rw.py XXXX search_under_age 2

上の 2 つのコマンドを何回か繰り返し実行してみて,データベースに負荷をかけてみよう. とくに大きな遅延なく結果が返ってくることが確認できるだろう.

スタックの削除

DynamoDB で十分に遊ぶことができたら,忘れずにスタックを削除しよう.

これまでのハンズオンと同様,スタックを削除するには,次のコマンドを実行すればよい.

sh
$ cdk destroy
$ cdk destroy

S3 ハンズオン

最後に, S3 の簡単なチュートリアルを紹介する. ハンズオンのソースコードは GitHub の handson/serverless/s3 に置いてある.

figure_title が今回提供する S3 チュートリアルの概要である. STEP 1 として, AWS CDK を用いて S3 に新しい空のバケット (Bucket) を作成する. 続いて STEP 2 では,データのアップロード・ダウンロードの方法を解説する.

S3 チュートリアルの概要

このハンズオンは,基本的に S3 の無料枠 の範囲内で実行することができる.

app.py にデプロイするプログラムが書かれている. 中身を見てみよう.

python
class SimpleS3(core.Stack):
    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        # S3 bucket to store data
        bucket = s3.Bucket(
            self, "bucket",
            removal_policy=core.RemovalPolicy.DESTROY,
            auto_delete_objects=True,
        )
class SimpleS3(core.Stack):
    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        # S3 bucket to store data
        bucket = s3.Bucket(
            self, "bucket",
            removal_policy=core.RemovalPolicy.DESTROY,
            auto_delete_objects=True,
        )

s3.Bucket() を呼ぶことによって空のバケットが新規に作成される. 上記のコードだと,バケットの名前は自動生成される. もし,自分の指定した名前を与えたい場合は, bucket_name というパラメータを指定すればよい. その際, バケットの名前はユニークでなければならない (i.e. AWS のデプロイが行われるリージョン内で名前の重複がない) 点に注意しよう. もし,同じ名前のバケットが既に存在する場合はエラーが返ってくる.

デフォルトでは, CloudFormation スタックが削除されたとき, S3 バケットとその中に保存されたファイルは削除されない. これは,大切なデータを誤って消してしまうことを防止するための安全策である. cdk destroy を実行したときにバケットも含めてすべて削除されるようにするには, removal_policy=core.RemovalPolicy.DESTROY, auto_delete_objects=True とパラメータを設定する. 結果もよく理解したうえで,自分の用途にあった適切なパラメータを設定しよう.

デプロイ

デプロイの手順は,これまでのハンズオンとほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). シークレットキーの設定も忘れずに (AWS CLI のインストール).

sh
# プロジェクトのディレクトリに移動
$ cd handson/serverless/s3

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd handson/serverless/s3

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイを実行すると, figure_title のような出力が得られるはずである. ここで表示されている SimpleS3.BucketName = XXXX が,新しく作られたバケットの名前である (今回提供しているコードを使うとランダムな名前がバケットに割り当てられる). これはあとで使うのでメモしておこう.

デプロイ実行後の出力

データの読み書き

スタックのデプロイが完了したら,早速バケットにデータをアップロードしてみよう.

まずは,以下のコマンドを実行して, tmp.txt という仮のファイルを生成する.

sh
$ echo "Hello world!" >> tmp.txt
$ echo "Hello world!" >> tmp.txt

ハンズオンのディレクトリにある simple_s3.pyboto3 ライブラリを使用した S3 のファイルのアップロード・ダウンロードのスクリプトが書いてある. simple_s3.py を使って,上で作成した tmp.txt を以下のコマンドによりバケットにアップロードする. XXXX のところは,自分自身のバケットの名前で置き換えること.

sh
$ python simple_s3.py XXXX upload tmp.txt
$ python simple_s3.py XXXX upload tmp.txt

simple_s3.py のアップロードを担当している部分を以下に抜粋する.

python
def upload_file(bucket_name, filename, key=None):
    bucket = s3.Bucket(bucket_name)

    if key is None:
        key = os.path.basename(filename)

    bucket.upload_file(filename, key)
def upload_file(bucket_name, filename, key=None):
    bucket = s3.Bucket(bucket_name)

    if key is None:
        key = os.path.basename(filename)

    bucket.upload_file(filename, key)

bucket = s3.Bucket(bucket_name) の行で Bucket() オブジェクトを呼び出している. そして, upload_file() メソッドを呼ぶことでファイルのアップロードを実行している.

S3 においてファイルの識別子として使われるのが Key である. これは,従来的なファイルシステムにおけるパス (Path) と相同な概念で,それぞれのファイルに固有な Key が割り当てられる必要がある. Key という呼び方は, S3 が Object storage と呼ばれるシステムに立脚していることに由来する. --key のオプションを追加して simple_s3.py を実行することで, Key を指定してアップロードを実行することができる.

sh
$ python simple_s3.py XXXX upload tmp.txt --key a/b/tmp.txt
$ python simple_s3.py XXXX upload tmp.txt --key a/b/tmp.txt

ここではアップロードされたファイルに a/b/tmp.txt という Key を割り当てている.

ここまでコマンドを実行し終えたところで,一度 AWS コンソールに行き S3 の中身を確認してみよう. S3 のコンソールに行くと,バケットの一覧が見つかるはずである. その中から, simples3-bucket から始まるランダムな名前のついたバケットを探し,クリックする. するとバケットの中に含まれるファイルの一覧が表示される (figure_title).

S3 バケットの中のファイル一覧

ここで実行した 2 つのコマンドによって, tmp.txt というファイルと, a/b/tmp.txt というファイルが見つかることに注目しよう. 従来的なファイルシステムと似た体験を提供するため, S3 では Key が "/" (スラッシュ) によって区切られていた場合,ツリー状の階層構造によってファイルを管理することができる.

オブジェクトストレージには本来ディレクトリという概念はない. 上で紹介した "/" による階層づけはあくまでユーザー体験向上の目的のお化粧的な機能である.

次に,バケットからファイルのダウンロードを実行してみよう. simple_s3.py を使って,以下のコマンドを実行すればよい. XXXX のところは,自分自身のバケットの名前で置き換えること.

sh
$ python simple_s3.py XXXX download tmp.txt
$ python simple_s3.py XXXX download tmp.txt

simple_s3.py のダウンロードを担当している部分を以下に抜粋する.

python
def download_file(bucket_name, key, filename=None):
    bucket = s3.Bucket(bucket_name)

    if filename is None:
        filename = os.path.basename(key)

    bucket.download_file(key, filename)
def download_file(bucket_name, key, filename=None):
    bucket = s3.Bucket(bucket_name)

    if filename is None:
        filename = os.path.basename(key)

    bucket.download_file(key, filename)

S3 からのダウンロードはシンプルで, download_file() メソッドを使って,ダウンロードしたい対象の Key を指定すればよい. ローカルのコンピュータでの保存先のパスを 2 個目の引数として渡している.

スタックの削除

以上のハンズオンで, S3 の一番基本的な使い方を紹介した. ここまでのハンズオンが理解できたら,忘れずにスタックを削除しよう. これまでのハンズオンと同様,スタックを削除するには,次のコマンドを実行すればよい.

sh
$ cdk destroy
$ cdk destroy

Hands-on #6: Bashoutter

さて,最後のハンズオンとなる第六回では,これまで学んできたサーバーレスクラウドの技術を使って,簡単なウェブサービスを作ってみよう. 具体的には,人々が自分の作った俳句を投稿する SNS サービス (Bashoutter と名付ける) を作成してみよう. Lambda, DynamoDB, S3 などの技術をすべて盛り込み,シンプルながらもサーバーレスの利点を生かしたスケーラブルな SNS アプリが誕生する. 最終的には, figure_title のような,ミニマルではあるがとても現代風な SNS サイトが完成する!

ハンズオン#6で作製する SNS アプリケーション "Bashoutter"

準備

ハンズオンのソースコードは GitHub の handson/bashoutter に置いてある.

本ハンズオンの実行には,第一回ハンズオンで説明した準備 (準備) が整っていることを前提とする. それ以外に必要な準備はない.

このハンズオンは,基本的に AWS の無料枠 の範囲内で実行できる.

アプリケーションの説明

API

今回のアプリケーションでは,人々からの俳句の投稿を受け付けたり,投稿された俳句の一覧を取得する,といった機能を実装したい. この機能を実現するための最小限の設計として, table_title に示すような四つの REST API を今回は実装する. 俳句を投稿する,閲覧する,削除するという基本的なデータ操作を行うための API が完備されている. また, PATCH /haiku/{item_id} は, {item_id} で指定された俳句に”いいね”をするために使用する.

Bashoutter API

GET /haiku

俳句の一覧を取得する

POST /haiku

新しい俳句を投稿する

PATCH /haiku/{item_id}

{item_id} で指定された俳句にお気に入り票を一つ入れる

DELETE /haiku/{item_id}

{item_id} で指定された俳句を削除する

それぞれの API のパラメータおよび返り値の詳細は,ハンズオンのソースコードの中の swagger.yml に定義してある.

Open API Specification (OAS; 少し前は Swagger Specification とよばれていた) は, REST API のための記述フォーマットである. OAS に従って API の仕様が記述されていると,簡単にドキュメンテーションを生成したり,クライアントアプリケーションを自動生成することができる. 今回用意した API 仕様 も, OAS に従って書いてある. 詳しくは Swagger の公式ドキュメンテーション などを参照.

アプリケーションアーキテクチャ

このハンズオンで作成するアプリケーションの概要を figure_title に示す.

ハンズオン#5で作製するアプリケーションのアーキテクチャ

簡単にまとめると,次のような設計である.

  • クライアントからの API リクエストは, API Gateway (後述)にまず送信され, API の URI で指定された Lambda 関数へ転送される.

  • それぞれの API のパス (リソース) ごとに独立した Lambda を用意する.

  • 俳句の情報 (作者,本文,投稿日時など) を記録するためのデータベース (DynamoDB) を用意する.

  • 各 Lambda 関数には, DynamoDB へのアクセス権を付与する.

  • 最後に,ウェブブラウザからコンテンツを表示できるよう, ウェブページの静的コンテンツを配信するための S3 バケットを用意する.クライアントはこの S3 バケットにアクセスすることで HTML/CSS/JS などのコンテンツを取得する.

それでは,プログラムのソースコードを見てみよう (handson/bashoutter/app.py).

python
class Bashoutter(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        # dynamoDB table to store haiku
        table = ddb.Table(
            self, "Bashoutter-Table",
            partition_key=ddb.Attribute(
                name="item_id",
                type=ddb.AttributeType.STRING
            ),
            billing_mode=ddb.BillingMode.PAY_PER_REQUEST,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        #
        bucket = s3.Bucket(
            self, "Bashoutter-Bucket",
            website_index_document="index.html",
            public_read_access=True,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        common_params = {
            "runtime": _lambda.Runtime.PYTHON_3_7,
            "environment": {
                "TABLE_NAME": table.table_name
            }
        }

        #
        # define Lambda functions
        get_haiku_lambda = _lambda.Function(
            self, "GetHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.get_haiku",
            memory_size=512,
            **common_params,
        )
        post_haiku_lambda = _lambda.Function(
            self, "PostHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.post_haiku",
            **common_params,
        )
        patch_haiku_lambda = _lambda.Function(
            self, "PatchHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.patch_haiku",
            **common_params,
        )
        delete_haiku_lambda = _lambda.Function(
            self, "DeleteHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.delete_haiku",
            **common_params,
        )

        #
        # grant permissions
        table.grant_read_data(get_haiku_lambda)
        table.grant_read_write_data(post_haiku_lambda)
        table.grant_read_write_data(patch_haiku_lambda)
        table.grant_read_write_data(delete_haiku_lambda)

        #
        # define API Gateway
        api = apigw.RestApi(
            self, "BashoutterApi",
            default_cors_preflight_options=apigw.CorsOptions(
                allow_origins=apigw.Cors.ALL_ORIGINS,
                allow_methods=apigw.Cors.ALL_METHODS,
            )
        )

        haiku = api.root.add_resource("haiku")
        haiku.add_method(
            "GET",
            apigw.LambdaIntegration(get_haiku_lambda)
        )
        haiku.add_method(
            "POST",
            apigw.LambdaIntegration(post_haiku_lambda)
        )

        haiku_item_id = haiku.add_resource("{item_id}")
        haiku_item_id.add_method(
            "PATCH",
            apigw.LambdaIntegration(patch_haiku_lambda)
        )
        haiku_item_id.add_method(
            "DELETE",
            apigw.LambdaIntegration(delete_haiku_lambda)
        )
class Bashoutter(core.Stack):

    def __init__(self, scope: core.App, name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        #
        # dynamoDB table to store haiku
        table = ddb.Table(
            self, "Bashoutter-Table",
            partition_key=ddb.Attribute(
                name="item_id",
                type=ddb.AttributeType.STRING
            ),
            billing_mode=ddb.BillingMode.PAY_PER_REQUEST,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        #
        bucket = s3.Bucket(
            self, "Bashoutter-Bucket",
            website_index_document="index.html",
            public_read_access=True,
            removal_policy=core.RemovalPolicy.DESTROY
        )

        common_params = {
            "runtime": _lambda.Runtime.PYTHON_3_7,
            "environment": {
                "TABLE_NAME": table.table_name
            }
        }

        #
        # define Lambda functions
        get_haiku_lambda = _lambda.Function(
            self, "GetHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.get_haiku",
            memory_size=512,
            **common_params,
        )
        post_haiku_lambda = _lambda.Function(
            self, "PostHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.post_haiku",
            **common_params,
        )
        patch_haiku_lambda = _lambda.Function(
            self, "PatchHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.patch_haiku",
            **common_params,
        )
        delete_haiku_lambda = _lambda.Function(
            self, "DeleteHaiku",
            code=_lambda.Code.from_asset("api"),
            handler="api.delete_haiku",
            **common_params,
        )

        #
        # grant permissions
        table.grant_read_data(get_haiku_lambda)
        table.grant_read_write_data(post_haiku_lambda)
        table.grant_read_write_data(patch_haiku_lambda)
        table.grant_read_write_data(delete_haiku_lambda)

        #
        # define API Gateway
        api = apigw.RestApi(
            self, "BashoutterApi",
            default_cors_preflight_options=apigw.CorsOptions(
                allow_origins=apigw.Cors.ALL_ORIGINS,
                allow_methods=apigw.Cors.ALL_METHODS,
            )
        )

        haiku = api.root.add_resource("haiku")
        haiku.add_method(
            "GET",
            apigw.LambdaIntegration(get_haiku_lambda)
        )
        haiku.add_method(
            "POST",
            apigw.LambdaIntegration(post_haiku_lambda)
        )

        haiku_item_id = haiku.add_resource("{item_id}")
        haiku_item_id.add_method(
            "PATCH",
            apigw.LambdaIntegration(patch_haiku_lambda)
        )
        haiku_item_id.add_method(
            "DELETE",
            apigw.LambdaIntegration(delete_haiku_lambda)
        )
  • ここで,俳句の情報を記録しておくための DynamoDB テーブルを定義している.

  • 静的コンテンツを配信するための S3 バケットを用意している.

  • それぞれの API で実行される Lambda 関数を定義している. 関数は Python3.7 で書かれており,コードは handson/bashoutter/api/api.py にある.

  • <3> で定義された Lambda 関数に対し,データベースへの読み書きのアクセス権限を付与している.

  • ここで,API Gateway により,各 API パスとそこで実行されるべき Lambda 関数を紐付けている.

それぞれの項目について,もう少し詳しく説明しよう.

Public access mode の S3 バケット

S3 のバケットを作成しているコードを見てみよう.

python
bucket = s3.Bucket(
    self, "Bashoutter-Bucket",
    website_index_document="index.html",
    public_read_access=True,
    removal_policy=core.RemovalPolicy.DESTROY
)
bucket = s3.Bucket(
    self, "Bashoutter-Bucket",
    website_index_document="index.html",
    public_read_access=True,
    removal_policy=core.RemovalPolicy.DESTROY
)

ここで注目してほしいのは public_read_access=True の部分だ. 前章で, S3 について説明を行ったときには触れなかったが, S3 には Public access mode という機能がある. Public access mode をオンにしておくと,バケットの中のファイルは認証なしで (i.e. インターネット上の誰でも) 閲覧できるようになる. この設定は,一般公開されているウェブサイトの静的なコンテンツを置いておくのに最適であり,多くのサーバーレスによるウェブサービスでこのような設計が行われる. public access mode を設定しておくと, http://XXXX.s3-website-ap-northeast-1.amazonaws.com/ のような固有の URL がバケットに対して付与される. そして,クライアントがこの URL にアクセスをすると,バケットの中にある index.html がクライアントに返され,ページがロードされる (どのファイルが返されるかは, website_index_document="index.html" の部分で設定している.)

なお,この時点ではバケットは空である. HTML/CSS/JS など静的コンテンツの配置は,デプロイを行った後ほどのステップで行う.

より本格的なウェブページを運用する際には, public access mode の S3 バケットに, CloudFront という機能を追加することが一般的である. CloudFront により, Content Delivery Nework (CDN) や暗号化された HTTPS 通信を設定することができる. CloudFront についての詳細は 公式ドキュメンテーション "What is Amazon CloudFront?" などを参照いただきたい.

今回のハンズオンでは説明の簡略化のため CloudFront の設定を行わなかったが,興味のある読者は次のリンクのプログラムが参考になるだろう.

今回の S3 バケットには, AWS によって付与されたランダムな URL がついている. これを. example.com のような自分のドメインでホストしたければ, AWS によって付与された URL を自分のドメインの DNS レコードに追加すればよい.

API のハンドラ関数

API リクエストが来たときに,リクエストされた処理を行う関数のことをハンドラ (handler) 関数とよぶ. GET /haiku の API に対してのハンドラ関数を Lambda で定義している部分を見てみよう.

python
get_haiku_lambda = _lambda.Function(
    self, "GetHaiku",
    code=_lambda.Code.from_asset("api"),
    handler="api.get_haiku",
    memory_size=512,
    **common_params
)
get_haiku_lambda = _lambda.Function(
    self, "GetHaiku",
    code=_lambda.Code.from_asset("api"),
    handler="api.get_haiku",
    memory_size=512,
    **common_params
)

簡単なところから見ていくと, memory_size=512 の箇所でメモリーの使用量を 512MB に指定している. また, code=_lambda.Code.from_asset("api") によって外部のディレクトリ (api/) を参照せよと指定しており, handler="api.get_haiku" のところで api.py というファイルの get_haiku() という関数をハンドラ関数として実行せよ,と定義している.

次に,ハンドラ関数として使用されている get_haiku() のコードを見てみよう (handson/bashoutter/api/api.py).

python
ddb = boto3.resource("dynamodb")
table = ddb.Table(os.environ["TABLE_NAME"])

def get_haiku(event, context):
    """
    handler for GET /haiku
    """
    try:
        response = table.scan()

        status_code = 200
        resp = response.get("Items")
    except Exception as e:
        status_code = 500
        resp = {"description": f"Internal server error. {str(e)}"}
    return {
        "statusCode": status_code,
        "headers": HEADERS,
        "body": json.dumps(resp, cls=DecimalEncoder)
    }
ddb = boto3.resource("dynamodb")
table = ddb.Table(os.environ["TABLE_NAME"])

def get_haiku(event, context):
    """
    handler for GET /haiku
    """
    try:
        response = table.scan()

        status_code = 200
        resp = response.get("Items")
    except Exception as e:
        status_code = 500
        resp = {"description": f"Internal server error. {str(e)}"}
    return {
        "statusCode": status_code,
        "headers": HEADERS,
        "body": json.dumps(resp, cls=DecimalEncoder)
    }

response = table.scan() で,俳句の格納された DynamoDB テーブルから,すべての要素を取り出している. もしなにもエラーが起きなければステータスコード 200 が返され,もしなにかエラーが起こればステータスコード 500 が返されるようになっている.

上記のような操作を,ほかの API についても繰り返すことで,すべての API のハンドラ関数が定義されている.

GET /haiku のハンドラ関数で, response = table.scan() という部分があるが,実はこれは最善の書き方ではない. DynamoDB の scan() メソッドは,最大で 1MB までのデータしか返さない. データベースのサイズが大きく, 1MB 以上のデータがある場合には,再帰的に scan() メソッドをよぶ必要がある. 詳しくは boto3 ドキュメンテーション を参照.

AWS における権限の管理 (IAM)

以下の部分のコードに注目してほしい.

python
table.grant_read_data(get_haiku_lambda)
table.grant_read_write_data(post_haiku_lambda)
table.grant_read_write_data(patch_haiku_lambda)
table.grant_read_write_data(delete_haiku_lambda)
table.grant_read_data(get_haiku_lambda)
table.grant_read_write_data(post_haiku_lambda)
table.grant_read_write_data(patch_haiku_lambda)
table.grant_read_write_data(delete_haiku_lambda)

これまでは説明の簡略化のためにあえて触れてこなかったが, AWS には IAM (Identity and Access Management) という重要な概念がある. IAM は基本的に,あるリソースがほかのリソースに対してどのような権限をもっているか,を規定するものである. Lambda は,デフォルトの状態ではほかのリソースにアクセスする権限をなにも有していない. したがって, Lambda 関数が DynamoDB のデータを読み書きするためには,それを許可するような IAM が Lambda 関数に付与されていなければならない.

CDK による dynamodb.Table オブジェクトには grant_read_write_data() という便利なメソッドが備わっており,アクセスを許可したい Lambda 関数を引数としてこのメソッドを呼ぶことで,データベースへの読み書きを許可する IAM を付与することができる. 同様に,CDK の s3.Bucket オブジェクトにも grant_read_write() というメソッドが備わっており,これによってバケットへの読み書きを許可することができる. このメソッドは,実は Hands-on #4: AWS Batch を使って機械学習のハイパーパラメータサーチを並列化する で AWS Batch によるクラスターを構成した際に使用した. 興味のある読者は振り返ってコードを確認してみよう.

各リソースに付与する IAM は,必要最低限の権限を与えるにとどめるというのが基本方針である. これにより,セキュリティを向上させるだけでなく,意図していないプログラムからのデータベースへの読み書きを防止するという点で,バグを未然に防ぐことができる.

そのような理由により,このコードでは GET のハンドラー関数に対しては grant_read_data() によって, read 権限のみを付与している.

API Gateway

API Gateway とは, API の"入り口"として,API のリクエストパスに従って Lambda や EC2 などに接続を行うという機能を担う (figure_title). Lambda や EC2 によって行われた処理の結果は,再び API Gateway を経由してクライアントに返される. このように,クライアントとバックエンドサーバーの間に立ち, API のリソースパスに応じて接続先を振り分けるようなサーバーをルーター,あるいはリバースプロキシとよんだりする. 従来的には,ルーターにはそれ専用の仮想サーバーが置かれることが一般的であった. しかし, API Gateway はサーバーレスなルーターとして,固定されたサーバーを配置することなく, API のリクエストが来たときのみ起動し,API のルーティングを実行する. サーバーレスであることの当然の帰結として,アクセスの件数が増大したときにはそれにルーティングの処理能力を自動で増やす機能も備わっている.

API Gateway

API Gateway を配置することで,大量 (1 秒間に数千から数万件) の API リクエストに対応することのできるシステムを容易に構築することができる. API Gateway の料金は table_title のように設定されている. また,無料利用枠により,月ごとに 100 万件までのリクエストは 0 円で利用できる.

API Gateway の利用料金設定 (参照)
Number of Requests (per month)Price (per million)

First 333 million

$4.25

Next 667 million

$3.53

Next 19 billion

$3.00

Over 20 billion

$1.91

ソースコードの該当箇所を見てみよう.

python
#
api = apigw.RestApi(
    self, "BashoutterApi",
    default_cors_preflight_options=apigw.CorsOptions(
        allow_origins=apigw.Cors.ALL_ORIGINS,
        allow_methods=apigw.Cors.ALL_METHODS,
    )
)

#
haiku = api.root.add_resource("haiku")
#
haiku.add_method(
    "GET",
    apigw.LambdaIntegration(get_haiku_lambda)
)
haiku.add_method(
    "POST",
    apigw.LambdaIntegration(post_haiku_lambda)
)

#
haiku_item_id = haiku.add_resource("{item_id}")
#
haiku_item_id.add_method(
    "PATCH",
    apigw.LambdaIntegration(patch_haiku_lambda)
)
haiku_item_id.add_method(
    "DELETE",
    apigw.LambdaIntegration(delete_haiku_lambda)
)
#
api = apigw.RestApi(
    self, "BashoutterApi",
    default_cors_preflight_options=apigw.CorsOptions(
        allow_origins=apigw.Cors.ALL_ORIGINS,
        allow_methods=apigw.Cors.ALL_METHODS,
    )
)

#
haiku = api.root.add_resource("haiku")
#
haiku.add_method(
    "GET",
    apigw.LambdaIntegration(get_haiku_lambda)
)
haiku.add_method(
    "POST",
    apigw.LambdaIntegration(post_haiku_lambda)
)

#
haiku_item_id = haiku.add_resource("{item_id}")
#
haiku_item_id.add_method(
    "PATCH",
    apigw.LambdaIntegration(patch_haiku_lambda)
)
haiku_item_id.add_method(
    "DELETE",
    apigw.LambdaIntegration(delete_haiku_lambda)
)
  • 最初に, api = apigw.RestApi() により,空の API Gateway を作成している.

  • 次に, api.root.add_resource() のメソッドを呼ぶことで, /haiku という API パスを追加している.

  • 続いて, add_method() を呼ぶことで, GET, POST のメソッドを /haiku のパスに定義している.

  • さらに, haiku.add_resource("{item_id}") により, /haiku/{item_id} という API パスを追加している.

  • 最後に, add_method() を呼ぶことにより, PATCH, DELETE のメソッドを /haiku/{item_id} のパスに定義している.

このように, API Gateway の使い方は非常にシンプルで,逐次的に API パスとそこで実行されるメソッド・Lambda を記述していくだけでよい.

このプログラムで 新規 API を作成すると, ランダムな URL がその API のエンドポイントとして割り当てられる. これを. api.example.com のような自分のドメインでホストしたければ, AWS によって付与された URL を自分のドメインの DNS レコードに追加すればよい.

API Gateway で新規 API を作成したとき, default_cors_preflight_options= というパラメータで Cross Origin Resource Sharing (CORS) の設定を行っている. これは,ブラウザで走る Web アプリケーションと API を接続するときに必要な設定である.

アプリケーションのデプロイ

アプリケーションの中身が理解できたところで,早速デプロイを行ってみよう. デプロイの手順は,これまでのハンズオンとほとんど共通である. ここでは,コマンドのみ列挙する (# で始まる行はコメントである). シークレットキーの設定も忘れずに (AWS CLI のインストール).

sh
# プロジェクトのディレクトリに移動
$ cd intro-aws/handson/bashoutter

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy
# プロジェクトのディレクトリに移動
$ cd intro-aws/handson/bashoutter

# venv を作成し,依存ライブラリのインストールを行う
$ python3 -m venv .env
$ source .env/bin/activate
$ pip install -r requirements.txt

# デプロイを実行
$ cdk deploy

デプロイのコマンドが無事に実行されれば, figure_title のような出力が得られるはずである. ここで表示されている Bashoutter.BashoutterApiEndpoint = XXXX, Bashoutter.BucketUrl = YYYY の二つ文字列はあとで使うのでメモしておこう.

CDKデプロイ実行後の出力

AWS コンソールにログインして,デプロイされたスタックを確認してみよう. まずは,コンソールから API Gateway のページに行く. すると, figure_title のような画面が表示され,デプロイ済みの API エンドポイントの一覧が確認できる.

API Gateway コンソール画面 (1)

今回デプロイした "BashoutterApi" という名前の API をクリックすることで figure_title のような画面に遷移し,詳細情報を閲覧できる. GET /haiku, POST /haiku などが定義されていることが確認できる.

それぞれのメソッドをクリックすると,そのメソッドの詳細情報を確認できる. API Gateway は,前述したルーティングの機能だけでなく,認証機能などを追加することも可能である. このハンズオンではとくにこれらの機能は使用しないが, "Method Request" と書いてある項目などがそれに相当する. 次に, figure_title で画面右端の赤色で囲った部分に,この API で呼ばれる Lambda 関数が指定されていることに注目しよう. 関数名をクリックと,該当する Lambda のコンソールに遷移し,関数の中身を閲覧することが可能である.

API Gateway コンソール画面 (2)

次に, S3 のコンソール画面に移ってみよう. bashouter- で始まるランダムな名前のバケットが見つかるはずである (figure_title).

S3 コンソール画面

バケットの名前をクリックすることで,バケットの中身を確認してみよう. index.html のほか, css/, js/ などのディレクトリがあるのが確認できるだろう (figure_title). これらが,ウェブページの"枠"を定義している静的コンテンツである.

S3 バケットの中身

API リクエストを送信する

それでは,デプロイしたアプリケーションに対し,実際に API リクエストを送信してみよう. まずはコマンドラインから API を送信する演習を行おう. S3 に配置した GUI は一旦おいておく.

ここではコマンドラインから HTTP API リクエストを送信するためのシンプルな HTTP クライアントである HTTPie を使ってみよう. HTTPie は,スタックをデプロイするときに Python 仮想環境 (venv) を作成したとき,一緒にインストールされている. 念のためインストールがうまくいっているか確認するには,仮想環境を立ち上げたあとコマンドラインに http と打ってみる. ヘルプのメッセージが出力されたら準備 OK である.

まず,先ほどデプロイを実行したときに得られた API のエンドポイントの URL (Bashoutter.BashoutterApiEndpoint = XXXX で得られた XXXX の文字列) をコマンドラインの変数に設定しておく.

sh
$ export ENDPOINT_URL=XXXX
$ export ENDPOINT_URL=XXXX

次に,俳句の一覧を取得するため, GET /haiku の API を送信してみよう.

sh
$ http GET "${ENDPOINT_URL}/haiku"
$ http GET "${ENDPOINT_URL}/haiku"

現時点では,まだだれも俳句を投稿していないので,空の配列 ([]) が返ってくる.

それでは次に, POST /haiku を使って俳句を投稿してみよう.

sh
$ http POST "${ENDPOINT_URL}/haiku" \
username="松尾芭蕉" \
first="閑さや" \
second="岩にしみ入る" \
third="蝉の声"
$ http POST "${ENDPOINT_URL}/haiku" \
username="松尾芭蕉" \
first="閑さや" \
second="岩にしみ入る" \
third="蝉の声"

次のような出力が得られるだろう.

sh
HTTP/1.1 201 Created
Connection: keep-alive
Content-Length: 49
Content-Type: application/json
....
{
    "description": "Successfully added a new haiku"
}
HTTP/1.1 201 Created
Connection: keep-alive
Content-Length: 49
Content-Type: application/json
....
{
    "description": "Successfully added a new haiku"
}

新しい俳句を投稿することに成功したようである. 本当に俳句が追加されたか,再び GET リクエストを呼ぶことで確認してみよう.

sh
$ http GET "${ENDPOINT_URL}/haiku"

HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 258
Content-Type: application/json
...
[
    {
        "created_at": "2020-07-06T02:46:04+00:00",
        "first": "閑さや",
        "item_id": "7e91c5e4d7ad47909e0ac14c8bbab05b",
        "likes": 0.0,
        "second": "岩にしみ入る",
        "third": "蝉の声",
        "username": "松尾芭蕉"
    }
]
$ http GET "${ENDPOINT_URL}/haiku"

HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 258
Content-Type: application/json
...
[
    {
        "created_at": "2020-07-06T02:46:04+00:00",
        "first": "閑さや",
        "item_id": "7e91c5e4d7ad47909e0ac14c8bbab05b",
        "likes": 0.0,
        "second": "岩にしみ入る",
        "third": "蝉の声",
        "username": "松尾芭蕉"
    }
]

素晴らしい!

次に, PATCH /haiku/{item_id} を呼ぶことでこの俳句にいいねを追加してみよう. 一つ前のコマンドで取得した俳句の item_id を,次のコマンドの XXXX に代入した上で実行しよう.

sh
$ http PATCH "${ENDPOINT_URL}/haiku/XXXX"
$ http PATCH "${ENDPOINT_URL}/haiku/XXXX"

{"description": "OK"} という出力が得られるはずである. 再び GET リクエストを送ることで,いいね (likes) が 1 増えたことを確認しよう.

sh
$ http GET "${ENDPOINT_URL}/haiku"
...
[
    {
        ...
        "likes": 1.0,
        ...
    }
]
$ http GET "${ENDPOINT_URL}/haiku"
...
[
    {
        ...
        "likes": 1.0,
        ...
    }
]

最後に, DELETE リクエストを送ることで俳句をデータベースから削除しよう. XXXXitem_id の値で置き換えたうえで次のコマンドを実行する.

sh
$ http DELETE "${ENDPOINT_URL}/haiku/XXXX"
$ http DELETE "${ENDPOINT_URL}/haiku/XXXX"

再び GET リクエストを送ることで,返り値が空 ([]) になっていることを確認しよう.

これで,俳句の投稿・取得・削除そしていいねの追加,といった基本的な API がきちんと動作していることが確認できた.

大量の API リクエストをシミュレートする

さて,前節ではマニュアルで一つずつ俳句を投稿した. 多数のユーザーがいるような SNS では,1 秒間に数千件以上の投稿がされている. 今回はサーバーレスアーキテクチャを採用したことで,そのような瞬間的な大量アクセスにも容易に対応できるようなシステムが自動的に構築されている. このポイントを実証するため,ここでは大量の API が送信された状況をシミュレートしてみよう.

handson/bashoutter/client.py に,大量の API リクエストをシミュレートするためのプログラムが書かれている. このプログラムを使用すると, POST /haiku の API リクエストを指定された回数だけ実行することができる.

テストとして, API を 300 回実行してみよう. 次のコマンドを実行する.

sh
$ python client.py $ENDPOINT_URL post_many 300
$ python client.py $ENDPOINT_URL post_many 300

数秒のうちに実行が完了するだろう. これがもし,単一のサーバーからなる API だったとしたら,このような大量のリクエストの処理にはもっと時間がかかっただろう. 最悪の場合には,サーバーダウンにもつながっていたかもしれない. したがって,今回作成したサーバーレスアプリケーションは,とてもシンプルながらも 1 秒間に数百件の処理を行えるような,スケーラブルなクラウドシステムであることがわかる. サーバーレスでクラウドを設計することの利点を垣間見ることができただろうか?

先述のコマンドにより大量の俳句を投稿するとデータベースに無駄なデータがどんどん溜まってしまう. データベースを完全に空にするには,次のコマンドを使用する.

sh
$ python client.py $ENDPOINT_URL clear_database
$ python client.py $ENDPOINT_URL clear_database

Bashoutter GUI を動かしてみる

前節ではコマンドラインから API を送信する演習を行った. ウェブアプリケーションでは,これと同じことがウェブブラウザの背後で行われ,ページのコンテンツが表示されている (figure_title 参照). 最後に, API が GUI と統合されるとどうなるのか,見てみよう.

CDK のコードで, Public access mode の S3 バケットを作成したことを思い出してほしい. 最初のステップとして,ここにウェブサイトのコンテンツをアップロードしよう. ハンズオンのソースコードの中に gui/dist というフォルダが見つかるはずである. ここにはビルド済みのウェブサイトの静的コンテンツ (HTML/CSS/JavaScript) が入っている. AWS CLI のコマンドを使うことでこれらのファイルを S3 にアップロードしよう.

sh
$ aws s3 cp --recursive ./gui/dist s3://<BUCKET_NAME>
$ aws s3 cp --recursive ./gui/dist s3://<BUCKET_NAME>

コマンドを実行する際は, Bashoutter ハンズオンのディレクトリから行うこと (./gui/dist に注目),そして <BUCKET_NAME> にはデプロイした自身のバケットの名前が入る点に注意. 念のため,AWS コンソールにログインし,バケットにファイルがアップロードされている点を確認しておこう.

なお,今回は GUI の説明はとくに行わないが, Bashoutter のウェブサイトは Vue.jsVuetify という UI フレームワークを使って作成した. Vue を使うことで, Single page application (SPA) の技術でウェブサイトの画面がレンダリングされる. ソースコードは handson/bashoutter/gui のディレクトリの中にあるので,興味のある読者は確認してみるとよい.

アップトードが完了したところで,続いてデプロイを実行したときにコマンドラインの出力を見直してみよう. Bashoutter.BucketUrl= で与えられた URL が見つかるはずである (figure_title). これは,先述したとおり, Public access mode の S3 バケットの URL である.

ウェブブラウザを開き,アドレスバーに S3 の URL を入力しへアクセスしてみよう. すると, figure_title のようなページが表示されるはずである.

"Bashoutter" の GUI 画面

ページが表示されたら,一番上の "API Endpoint URL" と書いてあるテキストボックスに,今回デプロイした API Gateway の URL を入力する (今回のアプリケーションでは,API Gateway の URL はランダムに割り当てられるのでこのような GUI の仕様になっている). そうしたら,画面の "REFRESH" と書いてあるボタンを押してみよう. データベースに俳句が登録済みであれば,俳句の一覧が表示されるはずである. 各俳句の左下にあるハートのアイコンをクリックすることで, "like" の票を入れることができる.

新しい俳句を投稿するには,五七五と投稿者の名前を入力して, "POST" を押す. "POST" を押した後は,再び "REFRESH" ボタンを押すことで最新の俳句のリストをデータベースから取得する.

アプリケーションの削除

これで, Bashoutter プロジェクトが完成した! この SNS は,インターネットを通じて世界のどこからでもアクセスできる状態にある. また, 大量の API リクエストをシミュレートする で見たように,大量のユーザーの同時アクセスによる負荷がかかっても,柔軟にスケールが行われ遅延なく処理を行うことができる. 極めて簡素ながらも,立派なウェブサービスとしてのスペックは満たしているのである!

Bashoutter アプリを存分に楽しむことができたら,最後に忘れずにスタックを削除しよう.

コマンドラインからスタックの削除を実行するには,次のコマンドを使う.

sh
$ cdk destroy
$ cdk destroy

CDK のバージョンによっては S3 のバケットが空でないと, cdk destroy がエラーを出力する場合がある. この場合はスタックを削除する前に, S3 バケットの中身をすべて削除しなければならない.

コンソールから実行するには, S3 コンソールに行き,バケットの中身を開いたうえで,すべてのファイルを選択し, "Actions" → "Delete" を実行すればよいい.

コマンドラインから実行するには, 次のコマンドを使う. <BUCKET NAME> のところは,自分の バケットの名前 ("BashoutterBucketXXXX" というパターンの名前がついているはずである) に置き換えることを忘れずに.

sh
$ aws s3 rm <BUCKET NAME> --recursive
$ aws s3 rm <BUCKET NAME> --recursive

小括

ここまでが,本書第三部の内容であった.

第三部では,クラウドの応用として,一般の人に使ってもらうようなウェブアプリケーション・データベースをどのようにして作るのか,という点に焦点を当てて,説明を行った. その中で,従来的なクラウドシステムの設計と,ここ数年の最新の設計方法であるサーバーレスアーキテクチャについて解説した. Hands-on #5: サーバーレス入門 では, AWS でのサーバーレスの実践として, Lambda, S3, DynamoDB のハンズオンを行った. 最後に, Hands-on #6: Bashoutter では,これらの技術を統合することで,完全サーバーレスなウェブアプリケーション "Bashoutter" を作成した.

これらの演習を通じて,世の中のウェブサービスがどのようにしてでき上がっているのか,少し理解が深まっただろうか? また,そのようなウェブアプリケーションを自分が作りたいと思ったとき,今回のハンズオンがその出発点となることができたならば幸いである.

まとめ

Appendix: 環境構築

本書を読み進めるにあたって,ハンズオンのプログラムを実行するための環境を自分のローカルマシンにセットアップしなければならない. ここでは, AWS やコマンドラインの初心者を想定して,本章で必要なソフトウェアやライブラリのインストールなどを簡単に解説する. 以下に簡単な目次を示そう. 既に環境構築が済んでいる場合は適宜読み飛ばしていただき,関係のある箇所のみ目を通せば良い.

使用する OS は Linux/Mac/Windows のどれを用いても構わない. Windows のユーザーは, Windows Subsytem for Linux (WSL) を使用することを想定している (WSL のインストール).

また,本書のハンズオンを実行するための Docker イメージ を提供している. これを用いると, AWS CLI/CDK や Python の設定などをスキップできるので, Docker の使用方法を知っている読者には便利だろう.

AWS アカウントの取得

本書で提供するハンズオンを実際に自分で試すには,読者自身で AWS のアカウントの作成をする必要がある. 詳しいアカウントの作成の手順は 公式のドキュメンテーション に書かれているので,そちらも参照していただきたい. 以下の手順に従ってアカウントの作成を行う.

まず,ウェブブラウザから AWS コンソール にアクセスし,右上の Create an AWS Account をクリックする (figure_title で実線で囲った部分).

サインアップ (1): AWS コンソールにアクセス

次に,遷移した先のページでメールアドレスとパスワードなどの登録を行う (figure_title).

サインアップ (2): メールアドレス・パスワードなどの登録.

続いて,住所や電話番号などを訊かれるので,すべて入力しよう (figure_title).

サインアップ (3): 住所・電話番号の入力

次に,クレジットカードの情報の登録を求められる (figure_title). 個人で AWS を利用する場合は,利用料金の請求はクレジットカードを経由して行われる. クレジットカードの登録なしには AWS を使い始めることはできないことに注意.

サインアップ (4): クレジットカードの登録

次の画面では,携帯電話の SMS またはボイスメッセージを利用した本人確認が求められる (figure_title). 希望の認証方法を選択し,自分の携帯電話番号を入力しよう.

サインアップ (5): 携帯電話による本人確認

無事に本人確認が完了すると,最後にサポートプランの選択を求められる (figure_title). 無料の Basic support を選択しておけば問題ない.

サインアップ (6): サポートプランの選択

以上のステップにより,アカウントの作成が完了する (figure_title). 早速ログインをして, AWS コンソールにアクセスできるか確認しておこう.

サインアップ (7): アカウントの作成が完了した

AWS のシークレットキーの作成

AWS シークレットキーとは, AWS CLI や AWS CDK から AWS の API を操作するときに,ユーザー認証を行うための鍵のことである. AWS CLI/CDK を使うには,最初にシークレットキーを発行する必要がある. AWS シークレットキーの詳細は 公式ドキュメンテーション "Understanding and getting your AWS credentials" を参照.

  1. AWS コンソールにログインする.

  2. 画面右上のアカウント名をクリックし,表示されるプルダウンメニューから "My Security Credentials" を選択 (figure_title)

  3. "Access keys for CLI, SDK, & API access" の下にある "Create accesss key" のボタンをクリックする (figure_title)

  4. 表示された Access key ID, Secret access key を記録しておく (画面を閉じると二度と表示されない).

  5. 鍵を忘れてしまった場合などは,同じ手順で再発行が可能である.

  6. 発行したシークレットキーは, ~/.aws/credentials のファイルに書き込むか,環境変数に設定するなどして使う (詳しくは AWS CLI のインストール).

AWS シークレットキーの発行1

AWS シークレットキーの発行2

AWS Educate Starter Account を用いている場合は,次の手順でシークレットキーを確認する.

  • AWS Educate のコンソール画面から, vocareum のコンソールに移動する (figure_title).

  • Account Details をクリックし,続いて AWS CLI: Show をクリックする.

  • aws_access_key_id, aws_secret_access_key, aws_session_token が表示される (figure_title). ここで表示された内容を ~/.aws/credentials にコピーする (AWS CLI のインストール 参照). aws_session_token の箇所も漏らさずコピーすること.

  • 続いて, ~/.aws/config というファイルを用意し,次の内容を書き込む. 現時点では AWS Starter Account は us-east-1 リージョンでしか利用できないためである.

    [default] region = us-east-1 output = json

  • 上記の説明ではプロファイル名が default となっていたが,これは自分の好きな名前に変更してもよい. default 以外の名前を使用する場合は,コマンドを実行するときにプロファイル名を指定する必要がある (詳しくは AWS CLI のインストール).

vocareum コンソール

vocareum から AWS シークレットキーの発行

AWS CLI のインストール

読者のために,執筆時点におけるインストールの手順 (Linux 向け) を簡単に記述する. 将来のバージョンでは変更される可能性があるので,常に 公式のドキュメンテーション で最新の情報をチェックすることを忘れずに.

sh
$ curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
$ unzip awscliv2.zip
$ sudo ./aws/install
$ curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
$ unzip awscliv2.zip
$ sudo ./aws/install

インストールできたか確認するため,次のコマンドを打ってバージョン情報が出力されることを確認する.

sh
$ aws --version
$ aws --version

インストールができたら,次のコマンドにより初期設定を行う (参照).

sh
$ aws configure
$ aws configure

コマンドを実行すると, AWS Access Key ID, AWS Secret Access Key を入力するよう指示される. シークレットキーの発行については AWS のシークレットキーの作成 を参照. コマンドは加えて,Default region name を訊いてくる. ここには自分の好きな地域 (例えば ap-northeast-1 =東京リージョン) を指定すればよい. 最後の Default output formatjson としておくとよい.

このコマンドを完了すると, ~/.aws/credentials~/.aws/config という名前のファイルが生成されているはずである. 念のため, cat コマンドを使って中身を確認してみるとよい.

sh
$ cat ~/.aws/credentials
[default]
aws_access_key_id = XXXXXXXXXXXXXXXXXX
aws_secret_access_key = YYYYYYYYYYYYYYYYYYY

$ cat ~/.aws/config
[profile default]
region = ap-northeast-1
output = json
$ cat ~/.aws/credentials
[default]
aws_access_key_id = XXXXXXXXXXXXXXXXXX
aws_secret_access_key = YYYYYYYYYYYYYYYYYYY

$ cat ~/.aws/config
[profile default]
region = ap-northeast-1
output = json

~/.aws/credentials には認証鍵の情報が, ~/.aws/config には AWS CLI の設定が記録されている.

デフォルトでは, [default] という名前でプロファイルが保存される. いくつかのプロファイルを使い分けたければ, default の例に従って,たとえば [myprofile] などという名前でプロファイルを追加すればよい.

AWS CLI でコマンドを打つときに,プロファイルを使い分けるには,

sh
$ aws s3 ls --profile myprofile
$ aws s3 ls --profile myprofile

のように, --profile というオプションをつけてコマンドを実行する.

いちいち --profile オプションをつけるのが面倒だと感じる場合は, AWS_PROFILE という環境変数を設定するとよい.

sh
$ export AWS_PROFILE=myprofile
$ export AWS_PROFILE=myprofile

あるいは,認証情報などを環境変数に設定するテクニックもある.

sh
export AWS_ACCESS_KEY_ID=XXXXXX
export AWS_SECRET_ACCESS_KEY=YYYYYY
export AWS_DEFAULT_REGION=ap-northeast-1
export AWS_ACCESS_KEY_ID=XXXXXX
export AWS_SECRET_ACCESS_KEY=YYYYYY
export AWS_DEFAULT_REGION=ap-northeast-1

これらの環境変数は, ~/.aws/credentials よりも高い優先度をもつので,環境変数が設定されていればそちらの情報が使用される (参照).

AWS Educate Starter Accountus-east-1 のリージョンのみ利用可能である (執筆時点での情報). よって, AWS Educate Starter Account を使用している場合は, default region を us-east-1 に設定する必要がある.

AWS CDK のインストール

読者のために,執筆時点におけるインストールの手順 (Linux 向け) を簡単に記述する. 将来のバージョンでは変更される可能性があるので,常に 公式のドキュメンテーション で最新の情報をチェックすることを忘れずに.

Node.js がインストールされていれば,基本的に次のコマンドを実行すればよい.

sh
$ sudo npm install -g aws-cdk
$ sudo npm install -g aws-cdk

本書のハンズオンは AWS CDK version 1.100.0 で開発した. CDK は開発途上のライブラリなので,将来的に API が変更される可能性がある. API の変更によりエラーが生じた場合は, version 1.100.0 を使用することを推奨する.

sh
$ npm install -g aws-cdk@1.100
$ npm install -g aws-cdk@1.100

インストールできたか確認するため,次のコマンドを打って正しくバージョンが表示されることを確認する.

sh
$ cdk --version
$ cdk --version

インストールができたら,次のコマンドにより AWS 側の初期設定を行う. これは一度実行すれば OK.

sh
$ cdk bootstrap
$ cdk bootstrap

cdk bootstrap を実行するときは,AWS の認証情報とリージョンが正しく設定されていることを確認する. デフォルトでは ~/.aws/config にあるデフォルトのプロファイルが使用される. デフォルト以外のプロファイルを用いるときは AWS CLI のインストール で紹介したテクニックを使って切り替える.

AWS CDK の認証情報の設定は AWS CLI と基本的に同じである.詳しくは AWS CLI のインストール を参照.

WSL のインストール

本書のハンズオンではコマンドラインから AWS CLI のコマンドを実行したり, Python で書かれたプログラムを実行する. コマンドは基本的に UNIX のターミナルを想定して書かれている. Linux や Mac のユーザーは OS に標準搭載されているターミナルを用いれば良い. Windows を利用している読者は, Windows Subsystem for Linux (WSL) を利用することで,仮想の Linux 環境を構築することを推奨する. Cygwin などの Linux 環境をエミュレートするほかのツールでも構わないが,本書のプログラムは WSL でのみ動作確認を行っている.

WSL とは, Windows の OS 上で Linux の仮想環境を起動するための, Microsoft 社が公式で提供しているソフトウェアである. Ubuntu など希望の Linux distribution が選択でき,基本的にすべての Linux 向けに作られたプログラム・ソフトウェアを使用することができる.

執筆時点では WSL 2 が最新版として提供されているので,以下では WSL 2 のインストール手順を簡単に説明する. 細かな詳細などは, 公式ドキュメンテーション を参照のこと.

前提として,使用される OS は Windows 10 (Pro または Home エディション) でなければならない. さらに,使用している Windows 10 のバージョンが WSL に対応するバージョンであるかを確認する. X64 のシステムでは Version 1903, Build 18362 以上でなければならない. バージョンが対応していない場合は、 Windows のアップデートを行う.

まず最初に, Administrator 権限で PowerShell を起動する (figure_title). 左下の Windows メニューの検索バーに powershell と入力すると, PowerShell のプログラムが見つかるはずである, これを右クリックし、 Run as administrator を選択し起動する.

管理者権限での PowerShell の起動

PowerShell が起動したら、次のコマンドを実行する.

powershell
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

実行して、“The operation completed successfully.” と出力されるのを確認する. これで WSL が enable される.

次に,先ほどと同じ Administrator 権限で開いた PowerShell で次のコマンドを実行する。

powersh
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

実行して, “The operation completed successfully.” と出力されるのを確認する. これが確認出来たら、一度コンピュータを再起動する.

続いて, Linux kernel update package を次のリンクからダウンロードする. https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi

ダウンロードしたファイルをダブルクリックして実行する. ダイアログに従ってインストールを完了させる.

そうしたら,再び PowerShell を開き次のコマンドを実行する。

sh
wsl --set-default-version 2
wsl --set-default-version 2

最後に、自分の好みの Linux distribution をインストールする. ここでは Ubuntu 20.04 をインストールしよう.

Microsoft store のアプリを起動し,検索バーに Ubuntu と入力する. Ubuntu 20.04 LTS という項目が見つかるはずなので,それを開き, “Get” ボタンをクリックする (figure_title). しばらく待つと, Ubuntu 20.04 のインストールが完了する.

Microsoft store から Ubuntu 20.04 をインストール

Ubuntu 20.04 を初回に起動すると,初期設定が自動で開始され,数分待つことになる. 初期設定が終わると,ユーザー名・パスワードを設定するようプロンプトが出るので,プロンプトに従い入力する.

これで WSL2 のインストールが完了した. 早速 WSL2 を起動してみよう. 左下の Windows メニューの検索バーに Ubuntu と入力すると, Ubuntu 20.04 のプログラムが見つかるはずである (figure_title). クリックして起動しよう.

Ubuntu 20.04 の起動

すると,ターミナルの黒い画面が立ち上がるだろう (figure_title). ls, top などのコマンドを打ってみて, WSL がきちんと動作していることを確認しよう.

WSL の起動画面

オプションとして, Windows Terminal というマイクロソフトから提供されているツールを使うと,より快適に WSL を使用することができる. 興味のある読者はこちらのインストールも推奨する.

Docker のインストール

Docker のインストールの方法は OS によって異なる.

Mac ユーザーは, Docker Desktop をインストールする. インストールの方法は, Docker のウェブサイト から, Mac 版の Docker Desktop をダウンロードし,ダウンロードされたファイルをダブルクリックし, Applications のフォルダにドラッグするだけで良い. 詳細は 公式ドキュメンテーション を参照のこと.

Windows のユーザーは,Docker Desktop をインストールする. その際, WSL 2 が事前にインストールされていなければならない. 詳細は 公式ドキュメンテーション を参照のこと. Docker Desktop をインストールすると, WSL からも docker コマンドが使用できるようになる.

Linux ユーザー (特に Ubuntu ユーザー) については,インストールの方法はいくつかのアプローチがある. 公式ドキュメンテーション にいくつかのインストールの方法が示されているので,詳しい情報はそちらを参照いただきたい.

最も簡単な方法は, Docker が公式で提供しているインストールスクリプトを用いる方法である. この場合,次のコマンドを実行することで Docker がインストールされる.

sh
$ curl -fsSL https://get.docker.com -o get-docker.sh
$ sudo sh get-docker.sh
$ curl -fsSL https://get.docker.com -o get-docker.sh
$ sudo sh get-docker.sh

デフォルトのインストールでは, root ユーザーのみが docker コマンドを使用できる設定になっている. 従って,コマンドには毎回 sudo を付け加える必要がある. これが面倒だと感じる場合は,次のステップにより,使用するユーザーを docker というグループに追加する (詳細は 公式ドキュメンテーション "Post-installation steps for Linux" を参照).

まず最初に, docker という名前にグループを追加する. インストールによっては,既に docker グループが作られている場合もある.

sh
$ sudo groupadd docker
$ sudo groupadd docker

次に,現在使用しているユーザーを docker グループに加える.

sh
$ sudo usermod -aG docker $USER
$ sudo usermod -aG docker $USER

ここまでできたら,一度ログアウトし,再度ログインする. これによって,グループの変更がターミナルのセッションに反映される.

設定が正しくできているかを確認するため,次のコマンドを実行してみる.

sh
$ docker run hello-world
$ docker run hello-world

sudo なしでコンテナが実行できたならば,設定は完了である.

Python venv クイックガイド

他人からもらったプログラムで, numpy や scipy のバージョンが違う!などの理由で,プログラムが動かない,という経験をしたことがある人は多いのではないだろうか. もし,自分の計算機の中に一つしか Python 環境がないとすると,プロジェクトを切り替えるごとに正しいバージョンをインストールし直さなければならず,これは大変な手間である.

コードのシェアをよりスムーズにするためには,ライブラリのバージョンはプロジェクトごとに管理されるべきである. それを可能にするのが Python 仮想環境とよばれるツールであり, venv, pyenv, conda などがよく使われる.

そのなかでも, venv は Python に標準搭載されているのでとても便利である. pyenvconda は,別途インストールの必要があるが,それぞれの長所もある.

venv を使って仮想環境を作成するには,

sh
$ python -m venv .env
$ python -m venv .env

と実行する. これにより .env/ というディレクトリが作られ,このディレクトリに依存するライブラリが保存されることになる.

この新たな仮想環境を起動するには

sh
$ source .env/bin/activate
$ source .env/bin/activate

と実行する.

シェルのプロンプトに (.env) という文字が追加されていることを確認しよう (figure_title). これが, "いまあなたは venv の中にいますよ" というしるしになる.

venv を起動したときのプロンプト

仮想環境を起動すると,それ以降実行する pip コマンドは, .env/ 以下にインストールされる.このようにして,プロジェクトごとに使うライブラリのバージョンを切り分けることができる.

Python では requirements.txt というファイルに依存ライブラリを記述するのが一般的な慣例である.他人からもらったプログラムに, requirements.txt が定義されていれば,

sh
$ pip install -r requirements.txt
$ pip install -r requirements.txt

と実行することで,必要なライブラリをインストールし,瞬時に Python 環境を再現することができる.

venv による仮想環境を保存するディレクトリの名前は任意に選べることができるが, .env という名前を用いるのが一般的である.

ハンズオン実行用の Docker image の使い方

ハンズオンを実行するために必要な, Node.js, Python, AWS CDK などがインストールされた Docker image を用意した. これを使用することで,自分のローカルマシンに諸々をインストールする必要なく,すぐにハンズオンのコードが実行できる.

ハンズオンのいくつかのコマンドは Docker の外 = ローカルマシンのリアル環境で実行されなければならない. それらについてはハンズオンの該当箇所に注意書きとして記してある.

Docker イメージは Docker Hub においてある. Docker イメージのビルドファイルは GitHub の docker/Dockerfile にある.

次のコマンドでコンテナを起動する.

sh
$ docker run -it tomomano/labc:latest
$ docker run -it tomomano/labc:latest

初回にコマンドを実行したときのみ,イメージが Docker Hub からダウンロード (pull) される. 二回目以降はローカルにダウンロードされたイメージが使用される.

コンテナが起動すると,次のようなインタラクティブシェルが表示されるはずである (起動時に -it のオプションをつけたのがポイントである).

sh
root@aws-handson:~/programlisting
root@aws-handson:~/programlisting

この状態で ls コマンドを打つと, handson/ というディレクトリがあるはずである. ここに cd する.

sh
$ cd handson
$ cd handson

すると,各ハンズオンごとのディレクトリが見つかるはずである.

あとは,ハンズオンごとにディレクトリを移動し,ハンズオンごとの virtualenv を作成し,スタックのデプロイを行えばよい (プログラムを実行する など参照). ハンズオンごとに使用する依存ライブラリが異なるので,それぞれのハンズオンごとに virtualenv を作成するという設計になっている.

AWS の認証情報を設定することも忘れずに. AWS CLI のインストール で記述したように, AWS_ACCESS_KEY_ID などの環境変数を設定するのが簡単な方法である. あるいは,ローカルマシンの ~/.aws/credentials に認証情報が書き込まれているなら,このディレクトリをコンテナにマウントすることで,同じ認証ファイルをコンテナ内部から参照することが可能である. この選択肢を取る場合は,次のコマンドでコンテナを起動する.

sh
$ docker run -it -v ~/.aws:/root/.aws:ro tomomano/labc:latest
$ docker run -it -v ~/.aws:/root/.aws:ro tomomano/labc:latest

これにより,ローカルマシンの ~/.aws をコンテナの /root/.aws にマウントすることができる. 最後の :ro は read-only を意味する. 大切な認証ファイルが誤って書き換えられてしまわないように, read-only のフラグをつけることをおすすめする.

/root/ がコンテナ環境におけるホームディレクトリである. ここで紹介した認証ファイルをマウントするテクニックは, SSH 鍵をコンテナに渡すときなどにも使える.

ライセンス

本教科書およびハンズオンのソースコードは CC BY-NC-ND 4.0 に従うライセンスで公開しています.

教育など非商用の目的での本教科書の使用や再配布は自由に行うことが可能です. 商用目的で本書の全体またはその一部を無断で転載する行為は,これを固く禁じます.

]]>
<![CDATA[クラウドで行う科学計算・機械学習 ]]> https://note.toshiki.dev/development/aws/scientific-computing https://note.toshiki.dev/development/aws/scientific-computing Thu, 01 Jul 2021 00:00:00 GMT クラウドで行う科学計算・機械学習

計算機が発達した現代では,計算機によるシミュレーションやビッグデータの解析は,科学・エンジニアリングの研究の主要な柱である. これらの大規模な計算を実行するには,クラウドは最適である. 本章から始まる第二部では,どのようにしてクラウド上で科学計算を実行するのかを,ハンズオンとともに体験してもらう. 科学計算の具体的な題材として,今回は機械学習(深層学習)を取り上げる.

なお,本書では PyTorch ライブラリを使って深層学習のアルゴリズムを実装するが,深層学習および PyTorch の知識は不要である. 講義ではなぜ・どうやって深層学習をクラウドで実行するかに主眼を置いているので,実行するプログラムの詳細には立ち入らない. 将来,自分で深層学習を使う機会が来たときに,詳しく学んでもらいたい.

なぜ機械学習をクラウドで行うのか?

2010 年頃に始まった第三次 AI ブームのおかげで,学術研究だけでなく社会・ビジネスの文脈でも機械学習に高い関心が寄せられている. とくに,深層学習 (ディープラーニング) とよばれる多層のレイヤーからなるニューラルネットワークを用いたアルゴリズムは,画像認識や自然言語処理などの分野で圧倒的に高い性能を実現し,革命をもたらしている.

深層学習の特徴は,なんといってもそのパラメータの多さである. 層が深くなるほど,層間のニューロンを結ぶ重みパラメータの数が増大していく. たとえば,最新の言語モデルである GPT-3 には1750 億個ものパラメータが含まれている. このような膨大なパラメータを有することで,深層学習は高い表現力と汎化性能を実現しているのである.

GPT-3 に限らず,最近の SOTA (State-of-the-art) の性能を達成するニューラルネットワークでは,百万から億のオーダーのパラメータを内包することは頻繁になってきている. そのような巨大なニューラルネットを訓練 (最適化) させるのは,当然のことながら膨大な計算コストがかかる. 結果として,ひとつの計算機では丸一日以上の時間がかかる場合も珍しくない. 深層学習の発展の速度は目覚ましく,研究・ビジネス両方の観点からも,いかにスループットよくニューラルネットワークの最適化を行えるかが鍵となってくる. そのような問題を解決するのにとても有効な手段が,クラウドである! (#sec_first_ec2) でその片鱗を見たように,クラウドを使用することでゼロから数千に至るまでの数のインスタンスを動的に起動し,並列に計算を実行することができる. さらに,深層学習を加速させる目的で,深層学習の演算に専用設計された計算チップ (GPU など) がある. クラウドを利用すると,そのような専用計算チップも無尽蔵に利用することができる. 事実,先述した GPT-3 の学習も,詳細は明かされていないが,Microsoft 社のクラウドを使って行われたと報告されている.

GPU による深層学習の高速化

深層学習の計算で欠かすことのできない技術として, GPU (Graphics Processing Unit) について少し説明する.

GPU は,その名のとおり,元々はコンピュータグラフィックスを出力するための専用計算チップである. CPU (Central Processing Unit) に対し,グラフィックスの演算に特化した設計がなされている. 身近なところでは, XBox や PS5 などのゲームコンソールなどに搭載されているし,ハイエンドなノート型・デスクトップ型計算機にも搭載されていることがある. コンピュータグラフィックスでは,スクリーンにアレイ状に並んだ数百万個の画素をビデオレート (30 fps) 以上で処理する必要がある. そのため,GPU はコアあたりの演算能力は比較的小さいかわりに,チップあたり数百から数千のコアを搭載しており (figure_title),スクリーンの画素を並列的に処理することで,リアルタイムでの描画を実現している.

GPUのアーキテクチャ.GPUには数百から数千の独立した計算コアが搭載されている. (画像出典: https://devblogs.nvidia.com/nvidia-turing-architecture-in-depth/)

このように,コンピュータグラフィクスの目的で生まれた GPU だが,2010 年前後から,その高い並列計算能力をグラフィックス以外の計算 (科学計算など) に用いるという流れ (General-purpose computing on GPU; GPGPU) が生まれた. GPU のコアは,その設計から,行列の計算など,単純かつ規則的な演算が得意であり,そのような演算に対しては数個程度のコアしかもたない CPU に比べて圧倒的に高い計算速度を実現することができる. 現在では GPGPU は分子動力学や気象シミュレーション,そして機械学習など多くの分野で使われている.

ディープラーニングで最も頻繁に起こる演算が,ニューロンの出力を次の層のニューロンに伝える畳み込み (Convolution) 演算である (figure_title). 畳み込み演算は,まさに GPU が得意とする演算であり, CPU ではなく GPU を用いることで学習を飛躍的に (最大で数百倍程度) 加速させることができる.

ニューラルネットワークにおける畳み込み演算.

このように GPU は機械学習の計算で欠かせないものであるが,なかなか高価である. たとえば,科学計算・機械学習に専用設計された NVIDIA 社の Tesla V100 というチップは,一台で約百万円の価格が設定されている. 機械学習を始めるのに,いきなり百万円の投資はなかなか大きい. だが,クラウドを使えば,初期コスト0で GPU を使用することができる.

機械学習を行うのに, V100 が必ずしも必要というわけではない. むしろ,研究者などでしばしば行われるのは,コンピュータゲームに使われるグラフィックス用の GPU を買ってきて (NVIDIA GeForce シリーズなど),開発のときはをそれを用いる,というアプローチである. グラフィックス用のいわゆる"コンシューマ GPU"は,市場の需要が大きいおかげで,10 万円前後の価格で購入することができる. V100 と比べると,コンシューマ GPU はコアの数が少なかったり,メモリーが小さかったりなどで劣る点があるが, それらを除いては計算能力にとくに制限があるわけではなく,開発の段階では十分な性能である場合がほとんどである. プログラムができあがって,ビッグデータの解析や,モデルをさらに大きくしたいときなどに,クラウドは有効だろう.

クラウドで GPU を使うには, GPU が搭載された EC2 インスタンスタイプ (P3, P2, G3, G4 など) を選択しなければならない. table_title に,代表的な GPU 搭載のインスタンスタイプを挙げる (執筆時点での情報).

GPUを搭載したEC2インスタンスタイプ
InstanceGPUsGPU modelGPU Mem (GiB)vCPUMem (GiB)Price per hour ($)

p3.2xlarge

1

NVIDIA V100

16

8

61

3.06

p3n.16xlarge

8

NVIDIA V100

128

64

488

24.48

p2.xlarge

1

NVIDIA K80

12

4

61

0.9

g4dn.xlarge

1

NVIDIA T4

16

4

16

0.526

table_title からわかるとおり, CPU のみのインスタンスと比べると少し高い価格設定になっている. また,古い世代の GPU (V100 に対しての K80) はより安価な価格で提供されている. 1 インスタンスあたりの GPU の搭載数は 1 台から最大で 8 台まで選択することが可能である.

GPU を搭載した一番安いインスタンスタイプは, g4dn.xlarge であり,これには廉価かつ省エネルギー設計の NVIDIA T4 が搭載されている. 後のハンズオンでは,このインスタンスを使用して,ディープラーニングの計算を行ってみる.

table_title の価格は us-east-1 のものである. リージョンによって多少価格設定が異なる.

V100 を一台搭載した p3.2xlarge の利用料金は一時間あたり $3.06 である. V100 が約百万円で売られていることを考えると,約 3000 時間 (= 124 日間),通算で計算を行った場合に,クラウドを使うよりも V100 を自分で買ったほうがお得になる,という計算になる (実際には,自前で V100 を用意する場合は, V100 だけでなく, CPU やネットワーク機器,電気使用料も必要なので,百万円よりもさらにコストがかかる).

GPT-3 で使われた計算リソースの詳細は論文でも明かされていないのだが, Lambda 社のブログで興味深い考察が行われている (Lambda 社は機械学習に特化したクラウドサービスを提供している).

記事によると,1750 億のパラメータを訓練するには,一台の GPU (NVIDIA V100) を用いた場合,342 年の月日と 460 万ドルのクラウド利用料が必要となる,とのことである. GPT-3 のチームは,複数の GPU に処理を分散することで現実的な時間のうちに訓練を完了させたのであろうが,このレベルのモデルになってくるとクラウド技術の限界を攻めないと達成できないことは確かである.

深層学習を詳しく勉強したい人には以下の参考書を推薦したい. 深層学習の基礎的な概念や理論は普遍的であるが,この分野は日進月歩なので,常に最新の情報を取り入れることを忘れずに.

]]>
クラウドで行う科学計算・機械学習

計算機が発達した現代では,計算機によるシミュレーションやビッグデータの解析は,科学・エンジニアリングの研究の主要な柱である. これらの大規模な計算を実行するには,クラウドは最適である. 本章から始まる第二部では,どのようにしてクラウド上で科学計算を実行するのかを,ハンズオンとともに体験してもらう. 科学計算の具体的な題材として,今回は機械学習(深層学習)を取り上げる.

なお,本書では PyTorch ライブラリを使って深層学習のアルゴリズムを実装するが,深層学習および PyTorch の知識は不要である. 講義ではなぜ・どうやって深層学習をクラウドで実行するかに主眼を置いているので,実行するプログラムの詳細には立ち入らない. 将来,自分で深層学習を使う機会が来たときに,詳しく学んでもらいたい.

なぜ機械学習をクラウドで行うのか?

2010 年頃に始まった第三次 AI ブームのおかげで,学術研究だけでなく社会・ビジネスの文脈でも機械学習に高い関心が寄せられている. とくに,深層学習 (ディープラーニング) とよばれる多層のレイヤーからなるニューラルネットワークを用いたアルゴリズムは,画像認識や自然言語処理などの分野で圧倒的に高い性能を実現し,革命をもたらしている.

深層学習の特徴は,なんといってもそのパラメータの多さである. 層が深くなるほど,層間のニューロンを結ぶ重みパラメータの数が増大していく. たとえば,最新の言語モデルである GPT-3 には1750 億個ものパラメータが含まれている. このような膨大なパラメータを有することで,深層学習は高い表現力と汎化性能を実現しているのである.

GPT-3 に限らず,最近の SOTA (State-of-the-art) の性能を達成するニューラルネットワークでは,百万から億のオーダーのパラメータを内包することは頻繁になってきている. そのような巨大なニューラルネットを訓練 (最適化) させるのは,当然のことながら膨大な計算コストがかかる. 結果として,ひとつの計算機では丸一日以上の時間がかかる場合も珍しくない. 深層学習の発展の速度は目覚ましく,研究・ビジネス両方の観点からも,いかにスループットよくニューラルネットワークの最適化を行えるかが鍵となってくる. そのような問題を解決するのにとても有効な手段が,クラウドである! (#sec_first_ec2) でその片鱗を見たように,クラウドを使用することでゼロから数千に至るまでの数のインスタンスを動的に起動し,並列に計算を実行することができる. さらに,深層学習を加速させる目的で,深層学習の演算に専用設計された計算チップ (GPU など) がある. クラウドを利用すると,そのような専用計算チップも無尽蔵に利用することができる. 事実,先述した GPT-3 の学習も,詳細は明かされていないが,Microsoft 社のクラウドを使って行われたと報告されている.

GPU による深層学習の高速化

深層学習の計算で欠かすことのできない技術として, GPU (Graphics Processing Unit) について少し説明する.

GPU は,その名のとおり,元々はコンピュータグラフィックスを出力するための専用計算チップである. CPU (Central Processing Unit) に対し,グラフィックスの演算に特化した設計がなされている. 身近なところでは, XBox や PS5 などのゲームコンソールなどに搭載されているし,ハイエンドなノート型・デスクトップ型計算機にも搭載されていることがある. コンピュータグラフィックスでは,スクリーンにアレイ状に並んだ数百万個の画素をビデオレート (30 fps) 以上で処理する必要がある. そのため,GPU はコアあたりの演算能力は比較的小さいかわりに,チップあたり数百から数千のコアを搭載しており (figure_title),スクリーンの画素を並列的に処理することで,リアルタイムでの描画を実現している.

GPUのアーキテクチャ.GPUには数百から数千の独立した計算コアが搭載されている. (画像出典: https://devblogs.nvidia.com/nvidia-turing-architecture-in-depth/)

このように,コンピュータグラフィクスの目的で生まれた GPU だが,2010 年前後から,その高い並列計算能力をグラフィックス以外の計算 (科学計算など) に用いるという流れ (General-purpose computing on GPU; GPGPU) が生まれた. GPU のコアは,その設計から,行列の計算など,単純かつ規則的な演算が得意であり,そのような演算に対しては数個程度のコアしかもたない CPU に比べて圧倒的に高い計算速度を実現することができる. 現在では GPGPU は分子動力学や気象シミュレーション,そして機械学習など多くの分野で使われている.

ディープラーニングで最も頻繁に起こる演算が,ニューロンの出力を次の層のニューロンに伝える畳み込み (Convolution) 演算である (figure_title). 畳み込み演算は,まさに GPU が得意とする演算であり, CPU ではなく GPU を用いることで学習を飛躍的に (最大で数百倍程度) 加速させることができる.

ニューラルネットワークにおける畳み込み演算.

このように GPU は機械学習の計算で欠かせないものであるが,なかなか高価である. たとえば,科学計算・機械学習に専用設計された NVIDIA 社の Tesla V100 というチップは,一台で約百万円の価格が設定されている. 機械学習を始めるのに,いきなり百万円の投資はなかなか大きい. だが,クラウドを使えば,初期コスト0で GPU を使用することができる.

機械学習を行うのに, V100 が必ずしも必要というわけではない. むしろ,研究者などでしばしば行われるのは,コンピュータゲームに使われるグラフィックス用の GPU を買ってきて (NVIDIA GeForce シリーズなど),開発のときはをそれを用いる,というアプローチである. グラフィックス用のいわゆる"コンシューマ GPU"は,市場の需要が大きいおかげで,10 万円前後の価格で購入することができる. V100 と比べると,コンシューマ GPU はコアの数が少なかったり,メモリーが小さかったりなどで劣る点があるが, それらを除いては計算能力にとくに制限があるわけではなく,開発の段階では十分な性能である場合がほとんどである. プログラムができあがって,ビッグデータの解析や,モデルをさらに大きくしたいときなどに,クラウドは有効だろう.

クラウドで GPU を使うには, GPU が搭載された EC2 インスタンスタイプ (P3, P2, G3, G4 など) を選択しなければならない. table_title に,代表的な GPU 搭載のインスタンスタイプを挙げる (執筆時点での情報).

GPUを搭載したEC2インスタンスタイプ
InstanceGPUsGPU modelGPU Mem (GiB)vCPUMem (GiB)Price per hour ($)

p3.2xlarge

1

NVIDIA V100

16

8

61

3.06

p3n.16xlarge

8

NVIDIA V100

128

64

488

24.48

p2.xlarge

1

NVIDIA K80

12

4

61

0.9

g4dn.xlarge

1

NVIDIA T4

16

4

16

0.526

table_title からわかるとおり, CPU のみのインスタンスと比べると少し高い価格設定になっている. また,古い世代の GPU (V100 に対しての K80) はより安価な価格で提供されている. 1 インスタンスあたりの GPU の搭載数は 1 台から最大で 8 台まで選択することが可能である.

GPU を搭載した一番安いインスタンスタイプは, g4dn.xlarge であり,これには廉価かつ省エネルギー設計の NVIDIA T4 が搭載されている. 後のハンズオンでは,このインスタンスを使用して,ディープラーニングの計算を行ってみる.

table_title の価格は us-east-1 のものである. リージョンによって多少価格設定が異なる.

V100 を一台搭載した p3.2xlarge の利用料金は一時間あたり $3.06 である. V100 が約百万円で売られていることを考えると,約 3000 時間 (= 124 日間),通算で計算を行った場合に,クラウドを使うよりも V100 を自分で買ったほうがお得になる,という計算になる (実際には,自前で V100 を用意する場合は, V100 だけでなく, CPU やネットワーク機器,電気使用料も必要なので,百万円よりもさらにコストがかかる).

GPT-3 で使われた計算リソースの詳細は論文でも明かされていないのだが, Lambda 社のブログで興味深い考察が行われている (Lambda 社は機械学習に特化したクラウドサービスを提供している).

記事によると,1750 億のパラメータを訓練するには,一台の GPU (NVIDIA V100) を用いた場合,342 年の月日と 460 万ドルのクラウド利用料が必要となる,とのことである. GPT-3 のチームは,複数の GPU に処理を分散することで現実的な時間のうちに訓練を完了させたのであろうが,このレベルのモデルになってくるとクラウド技術の限界を攻めないと達成できないことは確かである.

深層学習を詳しく勉強したい人には以下の参考書を推薦したい. 深層学習の基礎的な概念や理論は普遍的であるが,この分野は日進月歩なので,常に最新の情報を取り入れることを忘れずに.

]]>
<![CDATA[Serverless architecture ]]> https://note.toshiki.dev/development/aws/serverless https://note.toshiki.dev/development/aws/serverless Thu, 01 Jul 2021 00:00:00 GMT Serverless architecture

サーバーレスアーキテクチャ (Serverless architecture) あるいは サーバーレスコンピューティング (Serverless computing) とは,従来とは全く異なるアプローチに基づくクラウドシステムの設計方法である. 歴史的には, AWS が 2014 年に発表した Lamba がサーバーレスアーキテクチャの先駆けとされている. その後, Google や Microsoft などのクラウドプラットフォームも同様の機能の提供を開始している. サーバーレスアーキテクチャの利点は,スケーラブルなクラウドシステムを安価かつ簡易に作成できる点であり,近年いたるところで導入が進んでいる.

Serverless とは,文字どおりの意味としてはサーバーなしで計算をするということになるが,それは一体どういう意味だろうか? サーバーレスについて説明するためには,まずは従来的な, "serverful" とよばれるようなシステムについて解説しなければならない.

Serverful クラウド (従来型)

従来的なクラウドシステムのスケッチを figure_title に示す. クライアントから送信されたリクエストは,最初に API サーバーに送られる. API サーバーでは,リクエストの内容に応じてタスクが実行される. タスクには,API サーバーだけで完結できるものもあるが,多くの場合,データベースの読み書きが必要である. データベースには,データベース専用の独立したサーバーマシンが用いられることが一般的である. また,画像や動画などの容量の大きいデータは,また別のストレージサーバーに保存されることが多い. これらの API サーバー,データベースサーバー,ストレージサーバーはそれぞれ独立したサーバーマシンであり, AWS の言葉では EC2 による仮想インスタンスを想定してもらったらよい.

多くのウェブサービスでは,多数のクライアントからのリクエストを処理するため,複数のサーバーマシンがクラウド内で起動し,負荷を分散するような設計がなされている. クライアントから来たリクエストを計算容量に余裕のあるサーバーに振り分けるような操作を Load balancing とよび,そのような操作を担当するマシンのことを Load balancer という.

計算負荷を分散する目的で多数のインスタンスを起動するのはよいのだが,計算負荷が小さすぎてアイドリング状態にあるようではコストと電力の無駄遣いである. したがって,すべてのサーバーが常に目標とする計算負荷を維持するよう,計算の負荷に応じてクラスター内の仮想サーバーの数を動的に増減させるような仕組みが必要である. そのような仕組みをクラスターのスケーリングとよび,負荷の増大に応答して新しい仮想インスタンスをクラスターに追加する操作を scale-out,負荷の減少に応答してインスタンスをシャットダウンする操作を scale-in とよぶ. クラスターのスケーリングは, API サーバーではもちろんのこと,データベースサーバー・ストレージサーバーでも必要になる. ストレージサーバーでは,例えば頻繁にアクセスされるデータはキャッシュ領域に保存したり,データのコピーを複数作るなどのスケーリングが行われる. データベースサーバーも同様に,頻繁にアクセスされるデータのアクセスがパンクしてしまわないよう,分散的な処理が必要となる. このように,クラウドシステム内すべての箇所で,負荷が均一になるような調整が必要であり,開発者は多くの時間をそのチューニングに費やさなければならない. また,サービスの利用者の数などに応じてスケーリングの設定は常に見直される必要があり,継続的な開発が要求される.

さらに問題を複雑にするのは,API サーバーで処理されるべきタスクが,非一様な点である. 非一様であるとは,たとえばタスク A は 3000 ミリ秒の実行時間と 512MB のメモリーを消費し,別のタスク B は 1000 ミリ秒の実行時間と 128MB のメモリーを消費する,というような状況を指している. 一つのサーバーマシンが計算負荷が異なる複数のタスクを処理する場合,クラスターのスケーリングはより複雑になる. この状況をシンプルにするために,1サーバーで実行するタスクは1種類に限る,という設計も可能であるが,そうするとで生まれる弊害も多い (ほとんど使われないタスクに対してもサーバー一台をまるまる割り当てなければならない = ほとんどアイドリング状態になってしまう,など).

Serverful なクラウドシステム

Serverless クラウドへ

Serverful クラウド (従来型) で議論したように,クラスターのスケーリングはクラウドシステムの経済的効率とシステムの安定性を最大化するために必須の作業である. それを反映して,多くの開発者の時間が投資されてきた.

クラスターのスケーリングはすべての開発者が何度も繰り返し行ってきた作業であり,いくつかの側面をテンプレート化し,共通化することができたならば開発のコストを大幅に削減できるだろう. それを実現するには,根本的なレベルからクラウドシステムの設計を考え直す必要がある. スケーリングを前提として考えることで,もっとシンプルで見通しがよいクラウドシステムの設計の仕組みはないだろうか? そのような動機が,サーバーレスアーキテクチャが誕生する背後にあった.

従来の serverful なシステムでの最大の問題点は,サーバーをまるまる占有してしまうという点にある. すなわち, EC2 インスタンスを起動したとき,そのインスタンスは起動したユーザーだけが使えるものであり,計算のリソース (CPU や RAM) が独占的に割り当てられた状態になる. 固定した計算資源の割り当てがされてしまっているので,インスタンスの計算負荷が 0%であろうが 100%であろうが,均一の使用料金が起動時間に比例して発生する.

サーバーレスアーキテクチャは,このような 独占的に割り当てられた計算リソースというものを完全に廃止することを出発点とする. サーバーレスアーキテクチャでは,計算のリソースは,クラウドプロバイダーがすべて管理する. クライアントは,仮想インスタンスを一台まるごと借りるのではなく,計算のタスクの需要が生まれる毎に,実行したいプログラム・コマンドをクラウドに提出する. クラウドプロバイダーは,自身のもつ巨大な計算リソースから空きを探し,提出されたプログラムを実行し,実行結果をクライアントに返す. 言い換えると,計算リソースのスケーリングやアロケーションなどはクラウドプロバイダーが一手に引き受け,ユーザーはジョブをサブミットすることに注力する,という枠組みである. これを図示すると, figure_title のようになる.

従来のクラウドと Serverless クラウドの比較

サーバーレスクラウドでは,スケーリングはすべてクラウドプロバイダーが引き受けるので,スケーラビリティーが保証されている. クライアントが同時に大量のタスクを送信した場合でも,クラウドプロバイダー側の独自の仕組みによってすべてのタスクが遅延なく実行される. また,サーバーレスクラウドを利用することで,クラウドのコストは実際に使用した計算の総量 (稼働時間) で決定されることになる. これは,計算の実行総量に関わらずインスタンスの起動時間で料金が決定されていた従来のシステムと比べて大きな違いである.

サーバーレスクラウドは,従来のクラウドとは根本から異なったアプローチなので,コードの書き方やシステムの設計が大きく異なる. サーバーレスクラウドを開発・運用するには,サーバーレス固有の概念や用語に精通している必要がある. 以降では,実際にクラウドを動かしながら,サーバーレスをより具体的に体験していこう.

従来型の(仮想インスタンスをたくさん起動するような)クラウドシステムは,賃貸と似ているかもしれない. 部屋を借りるというのは,その部屋でどれだけの時間を過ごそうが,月々の家賃は一定である. 同様に,仮想サーバーも,それがどれほどの計算を行っているかに関わらず,一定の料金が時間ごとに発生する.

一方で,サーバーレスクラウドは,電気・水道・ガス料金 と似ている. こちらは,実際に使用した量に比例して料金が決定されている. サーバーレスクラウドも,実際に計算を行った総時間で料金が決まる仕組みになっている.

サーバーレスクラウドを構成するコンポーネント

サーバーレスアーキテクチャの概要がわかってきたところで,ここでは AWS においてサーバーレスクラウドを構成する様々なコンポーネントを紹介していこう. 特に, Lambda, S3, DynamoDB を取り上げ,解説する (figure_title). サーバーレスクラウドは,これらのコンポーネントを統合することで一つのシステムが出来上がる. ここでは, Lambda,S3,DynamoDB を利用する際に押さえておかなければならない知識を一通り説明しきる都合上,具体的なイメージがわきにくいかもしれない. が,続く (#sec_intro_serverless) でそれぞれについてハンズオン形式で演習を行うので,そこでさらに理解を深めれば大丈夫である.

Lambda, S3, DynamoDB のアイコン

Lambda

AWS でサーバーレスコンピューティングの中心を担うのが, Lambda である. Lambda の使い方を figure_title に図示している. Lambda の仕組みはシンプルで,まずユーザーは実行したいプログラムのコードを事前に登録しておく. プログラムは, Python, Node.js, Ruby などの主要な言語がサポートされている. Lambda に登録されたひとつひとつのプログラムを関数 (Function) とよぶ. そして,関数を実行したいときに,invoke コマンドを Lambda に送信する. Lambda では, invoke のリクエストを受け取るとただちに (数ミリセカンドから数百ミリセカンド程度の時間で) プログラムの実行を開始する. そして,実行結果をクライアントやその他の計算機に返す.

AWS Lambda

このように,Lambda では占有された仮想インスタンスは存在せず,実行を待っているプログラムだけがある状態である. invoke のリクエストに応じて,プログラムが AWS の巨大な計算機プールのどこかに配置され,実行される. 同時に複数のリクエストが来た場合でも, AWS はそれらを実行するための計算リソースを割り当て,並列的に処理を行ってくれる. 原理上は,数千から数万のリクエストが同時に来たとしても, Lambda はそれらを同時に実行することができる. このような,占有された仮想サーバーの存在なしに,動的に関数を実行するサービスのことを総称して FaaS (Function as a Service) とよぶ.

Lambda ではそれぞれの関数につき, 128MB から 10240MB のメモリーを使用することができる (執筆時点の仕様). また,実効的な CPU のパワーはメモリーの量に比例する形で割り当てられる. すなわち,タスクに割り当てたメモリーの量が多ければ多いほど,より多くの CPU リソースが割り当てられることになる (しかし, RAM と CPU パワーの具体的な換算表は AWS からは公開されていない). 実行時間は 100 ミリ秒の単位で記録され,実行時間に比例して料金が決定される. table_title は Lambda の利用料金表である (執筆時点で ap-north-east1 リージョンを選択した場合).

Lambda の料金表
Memory (MB)Price per 100ms

128

$0.0000002083

512

$0.0000008333

1024

$0.0000016667

3008

$0.0000048958

実行時間に比例する料金に追加して,リクエストを送信するごとに発生する料金が設定されている. これは,百万回のリクエストにつき $0.2 である. たとえば, 128MB のメモリーを使用する関数を,それぞれ 200 ミリ秒,合計で 100 万回実行した場合, 0.0000002083 * 2 * 10^6 + 0.2 = $0.6 の料金となる. ウェブサーバーのデータベースの更新など簡単な計算であれば,200 ミリ秒程度で実行できる関数も多いことから,100 万回データベースの更新を行ったとしても,たった $0.6 しかコストが発生しないことになる. また,コードが実行されず待機状態になっている場合は,発生する料金は 0 である. このように,実際に意味のある処理が行われた時間にのみ,料金が発生する仕組みになっている.

Lambda は比較的短時間で完了する,反復性の高いタスクの実行に向いている. データベースの読み書きはその典型的な例であるが,そのほかにも,画像のサイズをトリミングしたり,サーバーサイドで定期的に実行されるメンテナンス処理などの利用が考えられる. また,複数の Lambda をリレー式に繋げることも可能で,シンプルな処理を組み合わせることで複雑なロジックを表現することができる.

上述の Lambda の料金計算は,説明のためコストに寄与する要素をいくつか省いている点は承知いただきたい. 例えば, DynamoDB の読み書きに関する料金や,ネットワークの通信にかかわるコストが考慮されていない.

サーバーレスストレージ: S3

サーバーレスの概念は,ストレージにも拡張されている.

従来的なストレージ (ファイルシステム) では,必ずホストとなるマシンと OS が存在しなければならない. したがって,それほどパワーは必要ないまでも,ある程度の CPU リソースを割かなければならない. また,従来的なファイルシステムでは,データ領域のサイズは最初にディスクを初期化するときに決めなければならず,後から容量を増加させることはしばしば困難である (ZFS などのファイルシステムを使えばある程度は自由にファイルシステムのサイズを変更することは可能である). よって,従来的なクラウドでは,ストレージを借りる際にはあらかじめディスクのサイズを指定せねばならず,ディスクの中身が空であろうと満杯であろうと,同じ利用料金が発生することになる (figure_title).

Simple Storage Service (S3) は,サーバーレスなストレージシステムを提供する (figure_title). S3 は従来的なストレージシステムと異なり, OS に"マウントする”という概念はない. 基本的に API を通じてデータの読み書きの操作が行われる. また,データの冗長化や暗号化,バックアップの作成など,通常ならば OS と CPU が介在しなければならない操作も, API を通じて行うことができる. S3 では事前に決められたディスク領域のサイズはなく,データを入れれば入れた分だけ,保存領域は拡大していく (仕様上はペタバイトスケールのデータを保存することが可能である). ストレージにかかる料金は,保存してあるデータの総容量で決定される.

S3 と従来的なファイルシステムの比較

S3 を利用する際に,料金に関わってくる主要な事項をまとめたのが table_title である (us-east-1 リージョンのもの. 説明のため主要な事項のみ取り出している. 詳細は 公式ドキュメンテーション "Amazon S3 pricing" を参照).

S3 の利用料金
項目料金

Data storage (First 50TB)

$0.023 per GB per month

PUT, COPY, POST, LIST requests (per 1,000 requests)

$0.005

GET, SELECT, and all other requests (per 1,000 requests)

$0.0004

Data Transfer IN To Amazon S3 From Internet

$0

Data Transfer OUT From Amazon S3 To Internet

$0.09 per GB

第一に,データの保存には $0.025 per GB のコストが月ごとに発生する. したがって,1000GB のデータを S3 に一ヵ月保存した場合, $25 の料金が発生することになる. また,PUT, COPY, POST などのリクエスト (=データを書き込む操作) に対しては,データ容量に関係なく,1000 回ごとに $0.005 のコストが発生する. GET, SELECT などのリクエスト (=データを読み込む操作) に対しては,1000 回ごとに $0.0004 のコストが発生する. また, S3 はデータを外に取り出す際の通信にもコストが生じる. 執筆時点では,S3 からインターネットを通じて外部にデータを転送 (data-out) すると $0.09 per GB のコストが発生する. データをインターネットを通じて S3 に入れる (data-in) 通信は無料で行える. また, AWS の 同じ Region 内のサービス (Lambda や EC2 など) にデータを転送するのは無料である. AWS のリージョンをまたいだデータの転送にはコストが発生する. いずれにせよ,サーバーレスの概念に則り,すべての料金が従量課金制で決定される設定になっている.

サーバーレスデータベース: DynamoDB

サーバーレスの概念は,データベースにも適用することができる.

ここでいうデータベースとは, Web サービスなどにおけるユーザーや商品の情報を記録しておくための保存領域のことを指している. 従来的に有名なデータベースとしては MySQL, PostgreSQL, MongoDB などが挙げられる. データベースと普通のストレージの違いは,データの検索機能にある. 普通のストレージではデータは単純にディスクに書き込まれるだけだが, データベースでは検索がより効率的になるようなデータの配置がされたり, 頻繁にアクセスされるデータはメモリーにキャッシュされるなどの機能が備わっている. これにより,巨大なデータの中から,興味のある要素を高速に取得することができる.

このような検索機能を実現するには,当然 CPU の存在が必須である. したがって,従来的なデータベースを構築する際は,ストレージ領域に加えて,たくさんの CPU コアを搭載したマシンが用いられることが多い. また,データベースが巨大な場合は複数マシンにまたがった分散型のシステムが設計される. 分散型システムの場合は, Serverful クラウド (従来型) で議論したようにデータベースへのアクセス負荷に応じて適切なスケーリングがなされる必要がある.

DynamoDB は, AWS が提供しているサーバーレスな分散型データベースである. サーバーレスであるので,占有されたデータベース用仮想インスタンスは存在せず, API を通じてデータの書き込み・読み出し・検索などの操作を行う. S3 と同様に,データ保存領域の上限は定められておらず,データを入れれば入れた分だけ,保存領域は拡大していく. また,データベースへの負荷が増減したときのスケーリングは, DynamoDB が自動で行うので,ユーザーは心配する必要はない.

DynamoDB での利用料金の計算はやや複雑なのだが, "On-demand Capacity" というモードで使用した場合の料金に関わってくる主要な事項をまとめたのが table_title である (us-east-1 リージョンのもの. 詳細は 公式ドキュメンテーション "Pricing for On-Demand Capacity" を参照).

DynamoDB の利用料金
項目料金

Write request units

$1.25 per million write request units

Read request units

$0.25 per million read request units

Data storage

$0.25 per GB-month

DynamoDB ではデータの書き込み操作の単位を write request unit とよび,データの読み込み操作の単位を read request unit とよぶ. 基本的に, 1kB 以下のデータを一度書き込むと 1 write request unit を消費し,4kB 以下のデータを一度読み込むと 1 read request unit を消費する (詳しくは 公式ドキュメンテーション "Read/Write Capacity Mode" を参照のこと). write request units は 100 万回ごとに $1.25, read request units は 100 万回ごとに $0.25 のコストが設定されている. また,保存されたデータ容量に対して $0.25 per GB のコストが月ごとに発生する. DynamoDB は高速な検索機能などを備えたデータベースであるので, GB あたりのストレージコストは S3 に比べ 10 倍程度高い. DynamoDB のデータの転送に関わるコストは,同じリージョン内ならば data-in,data-out ともに $0 である. リージョンをまたいだ通信には別途コストが発生する.

その他のサーバーレスクラウドの構成要素

以上で紹介した Lambda, S3, DynamoDB がサーバーレスクラウドの中で最も使用する頻度が高いサービスになる. その他のサーバーレスクラウドの構成要素を以下に列挙する. いくつかについては,今後のハンズオンを行う中で改めて解説を行う.

  • API Gateway: API を構築する際のルーティングを担う. (#sec_bashoutter) で取り上げる.

  • Fargate: (#sec_fargate_qabot) で触れた Fargate も,サーバーレスクラウドの要素の一部である. Lambda との違いは,Lambda よりも大容量のメモリーや CPU を要するような計算などを行うことができる点が挙げられる.

  • Simple Notification Service (SNS): サーバーレスのサービス間でイベントをやり取りするためのサービス.

  • Step Functions: サーバーレスのサービス間のオーケストレーションを担う.

サーバーレスアーキテクチャは万能か?

この問いへの答えは,筆者は NO であると考える.

ここまで,サーバーレスの利点を強調して説明をしてきたが,まだまだ新しい技術なだけに,欠点,あるいはサーバーフルなシステムに劣る点は数多くある.

大きな欠点を一つあげるとすれば,サーバーレスのシステムは各クラウドプラットフォームに固有なものなので,特定のプラットフォームでしか運用できないシステムになってしまう点であろう. AWS で作成したサーバーレスのシステムを, Google のクラウドに移植するには,かなり大掛かりなプログラムの書き換えが必要になる. 一方, serverful なシステムであれば,プラットフォーム間のマイグレーションは比較的簡単に行うことができる. クラウドプロバイダーとしては,自社のシステムへの依存度を強めることで,顧客を離さないようにするという狙いがあるのだろう…

その他,サーバーレスコンピューティングの欠点や今後の課題などは,次の論文で詳しく議論されている. 興味のある読者はぜひ読んでいただきたい.

]]>
Serverless architecture

サーバーレスアーキテクチャ (Serverless architecture) あるいは サーバーレスコンピューティング (Serverless computing) とは,従来とは全く異なるアプローチに基づくクラウドシステムの設計方法である. 歴史的には, AWS が 2014 年に発表した Lamba がサーバーレスアーキテクチャの先駆けとされている. その後, Google や Microsoft などのクラウドプラットフォームも同様の機能の提供を開始している. サーバーレスアーキテクチャの利点は,スケーラブルなクラウドシステムを安価かつ簡易に作成できる点であり,近年いたるところで導入が進んでいる.

Serverless とは,文字どおりの意味としてはサーバーなしで計算をするということになるが,それは一体どういう意味だろうか? サーバーレスについて説明するためには,まずは従来的な, "serverful" とよばれるようなシステムについて解説しなければならない.

Serverful クラウド (従来型)

従来的なクラウドシステムのスケッチを figure_title に示す. クライアントから送信されたリクエストは,最初に API サーバーに送られる. API サーバーでは,リクエストの内容に応じてタスクが実行される. タスクには,API サーバーだけで完結できるものもあるが,多くの場合,データベースの読み書きが必要である. データベースには,データベース専用の独立したサーバーマシンが用いられることが一般的である. また,画像や動画などの容量の大きいデータは,また別のストレージサーバーに保存されることが多い. これらの API サーバー,データベースサーバー,ストレージサーバーはそれぞれ独立したサーバーマシンであり, AWS の言葉では EC2 による仮想インスタンスを想定してもらったらよい.

多くのウェブサービスでは,多数のクライアントからのリクエストを処理するため,複数のサーバーマシンがクラウド内で起動し,負荷を分散するような設計がなされている. クライアントから来たリクエストを計算容量に余裕のあるサーバーに振り分けるような操作を Load balancing とよび,そのような操作を担当するマシンのことを Load balancer という.

計算負荷を分散する目的で多数のインスタンスを起動するのはよいのだが,計算負荷が小さすぎてアイドリング状態にあるようではコストと電力の無駄遣いである. したがって,すべてのサーバーが常に目標とする計算負荷を維持するよう,計算の負荷に応じてクラスター内の仮想サーバーの数を動的に増減させるような仕組みが必要である. そのような仕組みをクラスターのスケーリングとよび,負荷の増大に応答して新しい仮想インスタンスをクラスターに追加する操作を scale-out,負荷の減少に応答してインスタンスをシャットダウンする操作を scale-in とよぶ. クラスターのスケーリングは, API サーバーではもちろんのこと,データベースサーバー・ストレージサーバーでも必要になる. ストレージサーバーでは,例えば頻繁にアクセスされるデータはキャッシュ領域に保存したり,データのコピーを複数作るなどのスケーリングが行われる. データベースサーバーも同様に,頻繁にアクセスされるデータのアクセスがパンクしてしまわないよう,分散的な処理が必要となる. このように,クラウドシステム内すべての箇所で,負荷が均一になるような調整が必要であり,開発者は多くの時間をそのチューニングに費やさなければならない. また,サービスの利用者の数などに応じてスケーリングの設定は常に見直される必要があり,継続的な開発が要求される.

さらに問題を複雑にするのは,API サーバーで処理されるべきタスクが,非一様な点である. 非一様であるとは,たとえばタスク A は 3000 ミリ秒の実行時間と 512MB のメモリーを消費し,別のタスク B は 1000 ミリ秒の実行時間と 128MB のメモリーを消費する,というような状況を指している. 一つのサーバーマシンが計算負荷が異なる複数のタスクを処理する場合,クラスターのスケーリングはより複雑になる. この状況をシンプルにするために,1サーバーで実行するタスクは1種類に限る,という設計も可能であるが,そうするとで生まれる弊害も多い (ほとんど使われないタスクに対してもサーバー一台をまるまる割り当てなければならない = ほとんどアイドリング状態になってしまう,など).

Serverful なクラウドシステム

Serverless クラウドへ

Serverful クラウド (従来型) で議論したように,クラスターのスケーリングはクラウドシステムの経済的効率とシステムの安定性を最大化するために必須の作業である. それを反映して,多くの開発者の時間が投資されてきた.

クラスターのスケーリングはすべての開発者が何度も繰り返し行ってきた作業であり,いくつかの側面をテンプレート化し,共通化することができたならば開発のコストを大幅に削減できるだろう. それを実現するには,根本的なレベルからクラウドシステムの設計を考え直す必要がある. スケーリングを前提として考えることで,もっとシンプルで見通しがよいクラウドシステムの設計の仕組みはないだろうか? そのような動機が,サーバーレスアーキテクチャが誕生する背後にあった.

従来の serverful なシステムでの最大の問題点は,サーバーをまるまる占有してしまうという点にある. すなわち, EC2 インスタンスを起動したとき,そのインスタンスは起動したユーザーだけが使えるものであり,計算のリソース (CPU や RAM) が独占的に割り当てられた状態になる. 固定した計算資源の割り当てがされてしまっているので,インスタンスの計算負荷が 0%であろうが 100%であろうが,均一の使用料金が起動時間に比例して発生する.

サーバーレスアーキテクチャは,このような 独占的に割り当てられた計算リソースというものを完全に廃止することを出発点とする. サーバーレスアーキテクチャでは,計算のリソースは,クラウドプロバイダーがすべて管理する. クライアントは,仮想インスタンスを一台まるごと借りるのではなく,計算のタスクの需要が生まれる毎に,実行したいプログラム・コマンドをクラウドに提出する. クラウドプロバイダーは,自身のもつ巨大な計算リソースから空きを探し,提出されたプログラムを実行し,実行結果をクライアントに返す. 言い換えると,計算リソースのスケーリングやアロケーションなどはクラウドプロバイダーが一手に引き受け,ユーザーはジョブをサブミットすることに注力する,という枠組みである. これを図示すると, figure_title のようになる.

従来のクラウドと Serverless クラウドの比較

サーバーレスクラウドでは,スケーリングはすべてクラウドプロバイダーが引き受けるので,スケーラビリティーが保証されている. クライアントが同時に大量のタスクを送信した場合でも,クラウドプロバイダー側の独自の仕組みによってすべてのタスクが遅延なく実行される. また,サーバーレスクラウドを利用することで,クラウドのコストは実際に使用した計算の総量 (稼働時間) で決定されることになる. これは,計算の実行総量に関わらずインスタンスの起動時間で料金が決定されていた従来のシステムと比べて大きな違いである.

サーバーレスクラウドは,従来のクラウドとは根本から異なったアプローチなので,コードの書き方やシステムの設計が大きく異なる. サーバーレスクラウドを開発・運用するには,サーバーレス固有の概念や用語に精通している必要がある. 以降では,実際にクラウドを動かしながら,サーバーレスをより具体的に体験していこう.

従来型の(仮想インスタンスをたくさん起動するような)クラウドシステムは,賃貸と似ているかもしれない. 部屋を借りるというのは,その部屋でどれだけの時間を過ごそうが,月々の家賃は一定である. 同様に,仮想サーバーも,それがどれほどの計算を行っているかに関わらず,一定の料金が時間ごとに発生する.

一方で,サーバーレスクラウドは,電気・水道・ガス料金 と似ている. こちらは,実際に使用した量に比例して料金が決定されている. サーバーレスクラウドも,実際に計算を行った総時間で料金が決まる仕組みになっている.

サーバーレスクラウドを構成するコンポーネント

サーバーレスアーキテクチャの概要がわかってきたところで,ここでは AWS においてサーバーレスクラウドを構成する様々なコンポーネントを紹介していこう. 特に, Lambda, S3, DynamoDB を取り上げ,解説する (figure_title). サーバーレスクラウドは,これらのコンポーネントを統合することで一つのシステムが出来上がる. ここでは, Lambda,S3,DynamoDB を利用する際に押さえておかなければならない知識を一通り説明しきる都合上,具体的なイメージがわきにくいかもしれない. が,続く (#sec_intro_serverless) でそれぞれについてハンズオン形式で演習を行うので,そこでさらに理解を深めれば大丈夫である.

Lambda, S3, DynamoDB のアイコン

Lambda

AWS でサーバーレスコンピューティングの中心を担うのが, Lambda である. Lambda の使い方を figure_title に図示している. Lambda の仕組みはシンプルで,まずユーザーは実行したいプログラムのコードを事前に登録しておく. プログラムは, Python, Node.js, Ruby などの主要な言語がサポートされている. Lambda に登録されたひとつひとつのプログラムを関数 (Function) とよぶ. そして,関数を実行したいときに,invoke コマンドを Lambda に送信する. Lambda では, invoke のリクエストを受け取るとただちに (数ミリセカンドから数百ミリセカンド程度の時間で) プログラムの実行を開始する. そして,実行結果をクライアントやその他の計算機に返す.

AWS Lambda

このように,Lambda では占有された仮想インスタンスは存在せず,実行を待っているプログラムだけがある状態である. invoke のリクエストに応じて,プログラムが AWS の巨大な計算機プールのどこかに配置され,実行される. 同時に複数のリクエストが来た場合でも, AWS はそれらを実行するための計算リソースを割り当て,並列的に処理を行ってくれる. 原理上は,数千から数万のリクエストが同時に来たとしても, Lambda はそれらを同時に実行することができる. このような,占有された仮想サーバーの存在なしに,動的に関数を実行するサービスのことを総称して FaaS (Function as a Service) とよぶ.

Lambda ではそれぞれの関数につき, 128MB から 10240MB のメモリーを使用することができる (執筆時点の仕様). また,実効的な CPU のパワーはメモリーの量に比例する形で割り当てられる. すなわち,タスクに割り当てたメモリーの量が多ければ多いほど,より多くの CPU リソースが割り当てられることになる (しかし, RAM と CPU パワーの具体的な換算表は AWS からは公開されていない). 実行時間は 100 ミリ秒の単位で記録され,実行時間に比例して料金が決定される. table_title は Lambda の利用料金表である (執筆時点で ap-north-east1 リージョンを選択した場合).

Lambda の料金表
Memory (MB)Price per 100ms

128

$0.0000002083

512

$0.0000008333

1024

$0.0000016667

3008

$0.0000048958

実行時間に比例する料金に追加して,リクエストを送信するごとに発生する料金が設定されている. これは,百万回のリクエストにつき $0.2 である. たとえば, 128MB のメモリーを使用する関数を,それぞれ 200 ミリ秒,合計で 100 万回実行した場合, 0.0000002083 * 2 * 10^6 + 0.2 = $0.6 の料金となる. ウェブサーバーのデータベースの更新など簡単な計算であれば,200 ミリ秒程度で実行できる関数も多いことから,100 万回データベースの更新を行ったとしても,たった $0.6 しかコストが発生しないことになる. また,コードが実行されず待機状態になっている場合は,発生する料金は 0 である. このように,実際に意味のある処理が行われた時間にのみ,料金が発生する仕組みになっている.

Lambda は比較的短時間で完了する,反復性の高いタスクの実行に向いている. データベースの読み書きはその典型的な例であるが,そのほかにも,画像のサイズをトリミングしたり,サーバーサイドで定期的に実行されるメンテナンス処理などの利用が考えられる. また,複数の Lambda をリレー式に繋げることも可能で,シンプルな処理を組み合わせることで複雑なロジックを表現することができる.

上述の Lambda の料金計算は,説明のためコストに寄与する要素をいくつか省いている点は承知いただきたい. 例えば, DynamoDB の読み書きに関する料金や,ネットワークの通信にかかわるコストが考慮されていない.

サーバーレスストレージ: S3

サーバーレスの概念は,ストレージにも拡張されている.

従来的なストレージ (ファイルシステム) では,必ずホストとなるマシンと OS が存在しなければならない. したがって,それほどパワーは必要ないまでも,ある程度の CPU リソースを割かなければならない. また,従来的なファイルシステムでは,データ領域のサイズは最初にディスクを初期化するときに決めなければならず,後から容量を増加させることはしばしば困難である (ZFS などのファイルシステムを使えばある程度は自由にファイルシステムのサイズを変更することは可能である). よって,従来的なクラウドでは,ストレージを借りる際にはあらかじめディスクのサイズを指定せねばならず,ディスクの中身が空であろうと満杯であろうと,同じ利用料金が発生することになる (figure_title).

Simple Storage Service (S3) は,サーバーレスなストレージシステムを提供する (figure_title). S3 は従来的なストレージシステムと異なり, OS に"マウントする”という概念はない. 基本的に API を通じてデータの読み書きの操作が行われる. また,データの冗長化や暗号化,バックアップの作成など,通常ならば OS と CPU が介在しなければならない操作も, API を通じて行うことができる. S3 では事前に決められたディスク領域のサイズはなく,データを入れれば入れた分だけ,保存領域は拡大していく (仕様上はペタバイトスケールのデータを保存することが可能である). ストレージにかかる料金は,保存してあるデータの総容量で決定される.

S3 と従来的なファイルシステムの比較

S3 を利用する際に,料金に関わってくる主要な事項をまとめたのが table_title である (us-east-1 リージョンのもの. 説明のため主要な事項のみ取り出している. 詳細は 公式ドキュメンテーション "Amazon S3 pricing" を参照).

S3 の利用料金
項目料金

Data storage (First 50TB)

$0.023 per GB per month

PUT, COPY, POST, LIST requests (per 1,000 requests)

$0.005

GET, SELECT, and all other requests (per 1,000 requests)

$0.0004

Data Transfer IN To Amazon S3 From Internet

$0

Data Transfer OUT From Amazon S3 To Internet

$0.09 per GB

第一に,データの保存には $0.025 per GB のコストが月ごとに発生する. したがって,1000GB のデータを S3 に一ヵ月保存した場合, $25 の料金が発生することになる. また,PUT, COPY, POST などのリクエスト (=データを書き込む操作) に対しては,データ容量に関係なく,1000 回ごとに $0.005 のコストが発生する. GET, SELECT などのリクエスト (=データを読み込む操作) に対しては,1000 回ごとに $0.0004 のコストが発生する. また, S3 はデータを外に取り出す際の通信にもコストが生じる. 執筆時点では,S3 からインターネットを通じて外部にデータを転送 (data-out) すると $0.09 per GB のコストが発生する. データをインターネットを通じて S3 に入れる (data-in) 通信は無料で行える. また, AWS の 同じ Region 内のサービス (Lambda や EC2 など) にデータを転送するのは無料である. AWS のリージョンをまたいだデータの転送にはコストが発生する. いずれにせよ,サーバーレスの概念に則り,すべての料金が従量課金制で決定される設定になっている.

サーバーレスデータベース: DynamoDB

サーバーレスの概念は,データベースにも適用することができる.

ここでいうデータベースとは, Web サービスなどにおけるユーザーや商品の情報を記録しておくための保存領域のことを指している. 従来的に有名なデータベースとしては MySQL, PostgreSQL, MongoDB などが挙げられる. データベースと普通のストレージの違いは,データの検索機能にある. 普通のストレージではデータは単純にディスクに書き込まれるだけだが, データベースでは検索がより効率的になるようなデータの配置がされたり, 頻繁にアクセスされるデータはメモリーにキャッシュされるなどの機能が備わっている. これにより,巨大なデータの中から,興味のある要素を高速に取得することができる.

このような検索機能を実現するには,当然 CPU の存在が必須である. したがって,従来的なデータベースを構築する際は,ストレージ領域に加えて,たくさんの CPU コアを搭載したマシンが用いられることが多い. また,データベースが巨大な場合は複数マシンにまたがった分散型のシステムが設計される. 分散型システムの場合は, Serverful クラウド (従来型) で議論したようにデータベースへのアクセス負荷に応じて適切なスケーリングがなされる必要がある.

DynamoDB は, AWS が提供しているサーバーレスな分散型データベースである. サーバーレスであるので,占有されたデータベース用仮想インスタンスは存在せず, API を通じてデータの書き込み・読み出し・検索などの操作を行う. S3 と同様に,データ保存領域の上限は定められておらず,データを入れれば入れた分だけ,保存領域は拡大していく. また,データベースへの負荷が増減したときのスケーリングは, DynamoDB が自動で行うので,ユーザーは心配する必要はない.

DynamoDB での利用料金の計算はやや複雑なのだが, "On-demand Capacity" というモードで使用した場合の料金に関わってくる主要な事項をまとめたのが table_title である (us-east-1 リージョンのもの. 詳細は 公式ドキュメンテーション "Pricing for On-Demand Capacity" を参照).

DynamoDB の利用料金
項目料金

Write request units

$1.25 per million write request units

Read request units

$0.25 per million read request units

Data storage

$0.25 per GB-month

DynamoDB ではデータの書き込み操作の単位を write request unit とよび,データの読み込み操作の単位を read request unit とよぶ. 基本的に, 1kB 以下のデータを一度書き込むと 1 write request unit を消費し,4kB 以下のデータを一度読み込むと 1 read request unit を消費する (詳しくは 公式ドキュメンテーション "Read/Write Capacity Mode" を参照のこと). write request units は 100 万回ごとに $1.25, read request units は 100 万回ごとに $0.25 のコストが設定されている. また,保存されたデータ容量に対して $0.25 per GB のコストが月ごとに発生する. DynamoDB は高速な検索機能などを備えたデータベースであるので, GB あたりのストレージコストは S3 に比べ 10 倍程度高い. DynamoDB のデータの転送に関わるコストは,同じリージョン内ならば data-in,data-out ともに $0 である. リージョンをまたいだ通信には別途コストが発生する.

その他のサーバーレスクラウドの構成要素

以上で紹介した Lambda, S3, DynamoDB がサーバーレスクラウドの中で最も使用する頻度が高いサービスになる. その他のサーバーレスクラウドの構成要素を以下に列挙する. いくつかについては,今後のハンズオンを行う中で改めて解説を行う.

  • API Gateway: API を構築する際のルーティングを担う. (#sec_bashoutter) で取り上げる.

  • Fargate: (#sec_fargate_qabot) で触れた Fargate も,サーバーレスクラウドの要素の一部である. Lambda との違いは,Lambda よりも大容量のメモリーや CPU を要するような計算などを行うことができる点が挙げられる.

  • Simple Notification Service (SNS): サーバーレスのサービス間でイベントをやり取りするためのサービス.

  • Step Functions: サーバーレスのサービス間のオーケストレーションを担う.

サーバーレスアーキテクチャは万能か?

この問いへの答えは,筆者は NO であると考える.

ここまで,サーバーレスの利点を強調して説明をしてきたが,まだまだ新しい技術なだけに,欠点,あるいはサーバーフルなシステムに劣る点は数多くある.

大きな欠点を一つあげるとすれば,サーバーレスのシステムは各クラウドプラットフォームに固有なものなので,特定のプラットフォームでしか運用できないシステムになってしまう点であろう. AWS で作成したサーバーレスのシステムを, Google のクラウドに移植するには,かなり大掛かりなプログラムの書き換えが必要になる. 一方, serverful なシステムであれば,プラットフォーム間のマイグレーションは比較的簡単に行うことができる. クラウドプロバイダーとしては,自社のシステムへの依存度を強めることで,顧客を離さないようにするという狙いがあるのだろう…

その他,サーバーレスコンピューティングの欠点や今後の課題などは,次の論文で詳しく議論されている. 興味のある読者はぜひ読んでいただきたい.

]]>
<![CDATA[Web サービスの作り方 ]]> https://note.toshiki.dev/development/aws/webserver https://note.toshiki.dev/development/aws/webserver Thu, 01 Jul 2021 00:00:00 GMT Web サービスの作り方

ここからが,本書第三部の内容になる. これまでのセクションでは,仮想サーバーをクラウド上に起動し,そこで計算を走らせる方法について解説をしてきた. EC2, ECS, Fargate, Batch などを利用して,動的にスケールするクラスターを構成し,並列にタスクを実行するクラウドシステムを実装してきた. 振り返ると,これまで紹介してきた内容は,自分自身が行いたい計算をクラウドを駆使することで実現する,という用途にフォーカスしていたことに気がつくだろう. 一方で,広く一般の人々に使ってもらえるような計算サービス・データベースを提供する,というのもクラウドの重要な役割として挙げられる.

本章から始まる第三部では,前回までとは少し方向性を変え,どのようにしてクラウド上にアプリケーションを展開し,広く一般の人に使ってもらうか,という点を講義したいと思う. これを通じて,どのようにして世の中のウェブサービスができ上がっているのかを知り,さらにどうやって自分でそのようなアプリケーションをゼロから構築するのか,という点を学んでもらう. その過程で,サーバーレスアーキテクチャという最新のクラウド設計手法を解説する.

その前準備として,本章ではどのようにしてウェブサービスが出来上がっているのか,その背後にある技術の概要を解説する. 用語の解説が中心となるが,後のハンズオンを実装するために必須の知識であるので,理解して前に進むよう心がけよう.

ウェブサービスの仕組み  — Twitter を例に

あなたがパソコンやスマートフォンから Twitter, Facebook, YouTube などのウェブサービスにアクセスしたとき,実際にどのようなことが行われ,コンテンツが提示されているのだろうか?

HTTP を通じたサーバーとクライアントのデータのやり取りは,すでに知っている読者も多いだろうし,逆にすべて解説しようとすると紙面が足りないので,ここではエッセンスの説明のみにとどめる. 以降では Twitter を具体例として,背後にあるサーバーとクライアントの間の通信を概説しよう. 概念図としては figure_title のような通信がクライアントとサーバーの間で行われていることになる.

クライアントと Web サーバーの通信の概念図

前提として,クライアントとサーバーの通信は HTTP (Hypertext Transfer Protocol) を使って行われる. また,最近では,暗号化された HTTP である HTTPS (HTTPS (Hypertext Transfer Protocol Secure)) を用いることがスタンダードになってきている. 第一のステップとして,クライアントは HTTP(S) 通信によってサーバーから静的なコンテンツを取得する. 静的なコンテンツとは, HTML (Hyptertext Markup Language) で記述されたウェブページの文書本体, CSS (Cascading Style Sheets) で記述されたページのデザインやレイアウトファイル,そして JavaScript (JS) で記述されたページの動的な挙動を定義したプログラム,が含まれる. Twitter を含む現代的なウェブアプリケーションの設計では,この静的なファイル群はページの”枠”を定義するだけで,中身となるコンテンツ (例: ツイートの一覧) は別途 API (Application Programming Interface) によって取得されなければならない. そこで,クライアントは先のステップで取得された JavaScript で定義されたプログラムに従って,サーバーに API を送信し,ツイートや画像データを取得する. この際,テキストデータのやり取りには JSON (JavaScript Object Notation) というフォーマットが用いられることが多い. 画像や動画などのコンテンツも同様に API により取得される. このようにして取得されたテキストや画像が,HTML の文書に埋め込まれることで,最終的にユーザーに提示されるページが完成するのである. また,新しいツイートを投稿するときにも,クライアントから API を通じてサーバーのデータベースにデータが書き込まれる.

REST API

API (Application Programming Interface) とはこれまで何度も出てきた言葉であるが,ここではよりフォーマルな定義付けを行う. API とはあるソフトウェア・アプリケーションが,外部のソフトウェアに対してコマンドやデータをやり取りするための媒介の一般的総称である. とくに,ウェブサービスの文脈では,サーバーが外界に対して提示しているコマンドの一覧のことを意味する. クライアントは,提示されている API から適切なコマンドを使うことによって,所望のデータを取得したり,あるいはサーバーにデータを送信したりする.

とくに,ウェブの文脈では REST (Representational State Transfer) とよばれる設計思想に基づいた API が現在では最も一般的に使われている. REST の設計指針に従った API のことを REST API あるいは RESTful API とよんだりする.

REST API は, figure_title に示したような MethodURI (Universal Resource Identifier) の組からなる.

REST API

Method (メソッド) とは,どのような操作を行いたいかを抽象的に表す,"動詞" として捉えることができる. メソッドには HTTP 規格で定義された 9 個の動詞 (verb) を使用することができる. この中でも, GET, POST, PUT, PATCH, DELETE の 5 個が最も頻繁に使用される (table_title). この 5 つのメソッドによる操作を総称して CRUD (create, read, update, and delete) とよぶ.

REST API Methods
メソッド意図される動作

GET

要素を取得する

POST

新しい要素を作成する

PUT

既存の要素を新しい要素と置き換える

PATCH

既存の要素の一部を更新する

DELETE

要素を削除する

一方, URI は操作が行われる対象,すなわち "目的語" を表す. ウェブの文脈では操作が行われる対象のことをしばしば リソース とよぶ. URI は多くの場合 http または https から始まるウェブサーバーのアドレスから始まり, / (スラッシュ) 以降に所望のリソースのパスが指定される. figure_title の例で言えば, https://api.twitter.com というアドレスの /1.1/status/home_timeline というリソースを取得 (GET) せよ,という意味になる (なお,ここで 1.1 という数字は API のバージョンを示している). この API リクエストによって,ユーザーのホームのタイムラインのツイートの一覧が取得される.

REST API のメソッドには, table_title で挙げたもの以外に, HTTP プロトコルで定義されているほかのメソッド (OPTIONS, TRACE など) を用いることもできるが,あまり一般的ではない.

また,これらのメソッドだけでは動詞として表現しきれないこともあるが, URI の名前でより意味を明確にすることもある. メソッドの使い方も,要素を削除する際は必ず DELETE を使わなければならない,という決まりもなく,たとえば, Twitter API でツイートを消す API は POST statuses/destroy/:id で定義されている. 最終的には,各ウェブサービスが公開している API ドキュメンテーションを読んで,それぞれの API がどんな操作をするのかを調べる必要がある.

REST の概念は 2000 年代初頭に確立され,今日の API 設計のスタンダードとなった. 一方で,ウェブのテクノロジーが進歩するにつれて,新たな API の設計アプローチの需要も高まっている. 近年とくに人気を集めているのが, GraphQL と呼ばれる API の設計方法である. GraphQL は Facebook 社によって最初に作られ,現在は GraghQL Foundation によって維持と更新がされている. GraphQL を使用すると,クライアントは REST と比較してより柔軟性の高いデータのクエリを行うことができるなど,いくつかの利点がある. キーワードだけでも知っておくと,今後役に立つだろう.

Twitter API

もう少し具体的にウェブサービスの API を体験する目的で,ここでは Twitter の API を見てみよう. Twitter が提供している API の一覧は Twitter の Developer Documentation で見ることができる. いくつかの代表的な API を table_title にまとめた.

Twitter API
エンドポイント動作

GET statuses/home_timeline

ホームのタイムラインのツイートの一覧を取得する.

GET statuses/show/:id

:id で指定されたツイートの詳細情報を取得する.

GET search

ツイートの検索を実行する.

POST statuses/update

新しいツイートを投稿する.

POST media/upload

画像をアップロードする

POST statuses/destroy/:id

:id で指定されたツイートを削除する.

POST statuses/retweet/:id

:id で指定されたツイートをリツイートする.

POST statuses/unretweet/:id

:id で指定されたツイートのリツイートを取り消す.

POST favorites/create

選択したツイートを"いいね"する.

POST favorites/destroy

選択したツイートを"いいね"を取り消す.

この API リストをもとに, Twitter のアプリまたはウェブサイトを開いたときに起こるクライアントとサーバーの通信をシミュレートしてみよう.

ユーザーが Twitter を開くと,まず最初に GET statuses/home_timeline の API リクエストによって,ユーザーのホームのタイムラインのツイートのリストが取得される. 個々のツイートは JSON 形式のデータになっており, id, text, user, coordinates, entities などの属性を含む. id はツイートに固有な ID を表し, text はツイートの本文を含んでいる. user はツイートを投稿したユーザーの名前やプロフィール画像の URL などを含んだ JSON データになっている. coordinates にはツイートが発信された地理的な座標が記録されている. また, entities にはツイートに関連するメディアファイル (画像など) のリンクなどの情報が埋め込まれている. GET statuses/home_timeline からは直近のツイートのリスト (リストが長すぎる場合は途中で切られたもの) が取得される. もしツイートの ID を知っている場合は GET statuses/show/:id を呼ぶことによって, :id パラメータで指定された特定のツイートを取得することができる.

ツイートの検索を行うためには GET search API を使用する. この API には,ツイートに含まれる単語や,ハッシュタグ,ツイートの発信された日時や場所など,様々なクエリの条件を渡すことができる. API からは, GET statuses/home_timeline などと同様, JSON 形式のツイートのデータが返される.

ユーザーが新しいツイートを投稿するには POST statuses/update のエンドポイントを利用する. POST statuses/update には,ツイートの文章や,リプライの場合はリプライ先のツイートの ID などのデータを送信する. また,ツイートに画像データを添付したい場合は, POST media/upload を併せて使用する. ツイートの削除を行うには, POST statuses/destroy/:id を用いる.

そのほか,頻繁に行われる操作としては, POST statuses/retweet/:idPOST statuses/unretweet/:id がある. これらは, :id で指定されるツイートに対して,それぞれリツイートを実行あるいは取り消すための API である. また, POST favorites/createPOST favorites/destroy を使用することによって,選択されたツイートに"いいね"を追加したり,取り消したりする操作を行う.

このような一連の操作が, Twitter のアプリの背後では行われている. また,自分自身でボットを作成したい場合は,これらの API を適切に組み合わせ,カスタムのプログラムを書くことで実現される.

このように, API はあらゆるウェブサービスを作るうえで一番基礎となる要素である. 次からの章では本章で紹介した用語が何度も出てくるので,頭の片隅に置いたうえで読み進めていただきたい.

]]>
Web サービスの作り方

ここからが,本書第三部の内容になる. これまでのセクションでは,仮想サーバーをクラウド上に起動し,そこで計算を走らせる方法について解説をしてきた. EC2, ECS, Fargate, Batch などを利用して,動的にスケールするクラスターを構成し,並列にタスクを実行するクラウドシステムを実装してきた. 振り返ると,これまで紹介してきた内容は,自分自身が行いたい計算をクラウドを駆使することで実現する,という用途にフォーカスしていたことに気がつくだろう. 一方で,広く一般の人々に使ってもらえるような計算サービス・データベースを提供する,というのもクラウドの重要な役割として挙げられる.

本章から始まる第三部では,前回までとは少し方向性を変え,どのようにしてクラウド上にアプリケーションを展開し,広く一般の人に使ってもらうか,という点を講義したいと思う. これを通じて,どのようにして世の中のウェブサービスができ上がっているのかを知り,さらにどうやって自分でそのようなアプリケーションをゼロから構築するのか,という点を学んでもらう. その過程で,サーバーレスアーキテクチャという最新のクラウド設計手法を解説する.

その前準備として,本章ではどのようにしてウェブサービスが出来上がっているのか,その背後にある技術の概要を解説する. 用語の解説が中心となるが,後のハンズオンを実装するために必須の知識であるので,理解して前に進むよう心がけよう.

ウェブサービスの仕組み  — Twitter を例に

あなたがパソコンやスマートフォンから Twitter, Facebook, YouTube などのウェブサービスにアクセスしたとき,実際にどのようなことが行われ,コンテンツが提示されているのだろうか?

HTTP を通じたサーバーとクライアントのデータのやり取りは,すでに知っている読者も多いだろうし,逆にすべて解説しようとすると紙面が足りないので,ここではエッセンスの説明のみにとどめる. 以降では Twitter を具体例として,背後にあるサーバーとクライアントの間の通信を概説しよう. 概念図としては figure_title のような通信がクライアントとサーバーの間で行われていることになる.

クライアントと Web サーバーの通信の概念図

前提として,クライアントとサーバーの通信は HTTP (Hypertext Transfer Protocol) を使って行われる. また,最近では,暗号化された HTTP である HTTPS (HTTPS (Hypertext Transfer Protocol Secure)) を用いることがスタンダードになってきている. 第一のステップとして,クライアントは HTTP(S) 通信によってサーバーから静的なコンテンツを取得する. 静的なコンテンツとは, HTML (Hyptertext Markup Language) で記述されたウェブページの文書本体, CSS (Cascading Style Sheets) で記述されたページのデザインやレイアウトファイル,そして JavaScript (JS) で記述されたページの動的な挙動を定義したプログラム,が含まれる. Twitter を含む現代的なウェブアプリケーションの設計では,この静的なファイル群はページの”枠”を定義するだけで,中身となるコンテンツ (例: ツイートの一覧) は別途 API (Application Programming Interface) によって取得されなければならない. そこで,クライアントは先のステップで取得された JavaScript で定義されたプログラムに従って,サーバーに API を送信し,ツイートや画像データを取得する. この際,テキストデータのやり取りには JSON (JavaScript Object Notation) というフォーマットが用いられることが多い. 画像や動画などのコンテンツも同様に API により取得される. このようにして取得されたテキストや画像が,HTML の文書に埋め込まれることで,最終的にユーザーに提示されるページが完成するのである. また,新しいツイートを投稿するときにも,クライアントから API を通じてサーバーのデータベースにデータが書き込まれる.

REST API

API (Application Programming Interface) とはこれまで何度も出てきた言葉であるが,ここではよりフォーマルな定義付けを行う. API とはあるソフトウェア・アプリケーションが,外部のソフトウェアに対してコマンドやデータをやり取りするための媒介の一般的総称である. とくに,ウェブサービスの文脈では,サーバーが外界に対して提示しているコマンドの一覧のことを意味する. クライアントは,提示されている API から適切なコマンドを使うことによって,所望のデータを取得したり,あるいはサーバーにデータを送信したりする.

とくに,ウェブの文脈では REST (Representational State Transfer) とよばれる設計思想に基づいた API が現在では最も一般的に使われている. REST の設計指針に従った API のことを REST API あるいは RESTful API とよんだりする.

REST API は, figure_title に示したような MethodURI (Universal Resource Identifier) の組からなる.

REST API

Method (メソッド) とは,どのような操作を行いたいかを抽象的に表す,"動詞" として捉えることができる. メソッドには HTTP 規格で定義された 9 個の動詞 (verb) を使用することができる. この中でも, GET, POST, PUT, PATCH, DELETE の 5 個が最も頻繁に使用される (table_title). この 5 つのメソッドによる操作を総称して CRUD (create, read, update, and delete) とよぶ.

REST API Methods
メソッド意図される動作

GET

要素を取得する

POST

新しい要素を作成する

PUT

既存の要素を新しい要素と置き換える

PATCH

既存の要素の一部を更新する

DELETE

要素を削除する

一方, URI は操作が行われる対象,すなわち "目的語" を表す. ウェブの文脈では操作が行われる対象のことをしばしば リソース とよぶ. URI は多くの場合 http または https から始まるウェブサーバーのアドレスから始まり, / (スラッシュ) 以降に所望のリソースのパスが指定される. figure_title の例で言えば, https://api.twitter.com というアドレスの /1.1/status/home_timeline というリソースを取得 (GET) せよ,という意味になる (なお,ここで 1.1 という数字は API のバージョンを示している). この API リクエストによって,ユーザーのホームのタイムラインのツイートの一覧が取得される.

REST API のメソッドには, table_title で挙げたもの以外に, HTTP プロトコルで定義されているほかのメソッド (OPTIONS, TRACE など) を用いることもできるが,あまり一般的ではない.

また,これらのメソッドだけでは動詞として表現しきれないこともあるが, URI の名前でより意味を明確にすることもある. メソッドの使い方も,要素を削除する際は必ず DELETE を使わなければならない,という決まりもなく,たとえば, Twitter API でツイートを消す API は POST statuses/destroy/:id で定義されている. 最終的には,各ウェブサービスが公開している API ドキュメンテーションを読んで,それぞれの API がどんな操作をするのかを調べる必要がある.

REST の概念は 2000 年代初頭に確立され,今日の API 設計のスタンダードとなった. 一方で,ウェブのテクノロジーが進歩するにつれて,新たな API の設計アプローチの需要も高まっている. 近年とくに人気を集めているのが, GraphQL と呼ばれる API の設計方法である. GraphQL は Facebook 社によって最初に作られ,現在は GraghQL Foundation によって維持と更新がされている. GraphQL を使用すると,クライアントは REST と比較してより柔軟性の高いデータのクエリを行うことができるなど,いくつかの利点がある. キーワードだけでも知っておくと,今後役に立つだろう.

Twitter API

もう少し具体的にウェブサービスの API を体験する目的で,ここでは Twitter の API を見てみよう. Twitter が提供している API の一覧は Twitter の Developer Documentation で見ることができる. いくつかの代表的な API を table_title にまとめた.

Twitter API
エンドポイント動作

GET statuses/home_timeline

ホームのタイムラインのツイートの一覧を取得する.

GET statuses/show/:id

:id で指定されたツイートの詳細情報を取得する.

GET search

ツイートの検索を実行する.

POST statuses/update

新しいツイートを投稿する.

POST media/upload

画像をアップロードする

POST statuses/destroy/:id

:id で指定されたツイートを削除する.

POST statuses/retweet/:id

:id で指定されたツイートをリツイートする.

POST statuses/unretweet/:id

:id で指定されたツイートのリツイートを取り消す.

POST favorites/create

選択したツイートを"いいね"する.

POST favorites/destroy

選択したツイートを"いいね"を取り消す.

この API リストをもとに, Twitter のアプリまたはウェブサイトを開いたときに起こるクライアントとサーバーの通信をシミュレートしてみよう.

ユーザーが Twitter を開くと,まず最初に GET statuses/home_timeline の API リクエストによって,ユーザーのホームのタイムラインのツイートのリストが取得される. 個々のツイートは JSON 形式のデータになっており, id, text, user, coordinates, entities などの属性を含む. id はツイートに固有な ID を表し, text はツイートの本文を含んでいる. user はツイートを投稿したユーザーの名前やプロフィール画像の URL などを含んだ JSON データになっている. coordinates にはツイートが発信された地理的な座標が記録されている. また, entities にはツイートに関連するメディアファイル (画像など) のリンクなどの情報が埋め込まれている. GET statuses/home_timeline からは直近のツイートのリスト (リストが長すぎる場合は途中で切られたもの) が取得される. もしツイートの ID を知っている場合は GET statuses/show/:id を呼ぶことによって, :id パラメータで指定された特定のツイートを取得することができる.

ツイートの検索を行うためには GET search API を使用する. この API には,ツイートに含まれる単語や,ハッシュタグ,ツイートの発信された日時や場所など,様々なクエリの条件を渡すことができる. API からは, GET statuses/home_timeline などと同様, JSON 形式のツイートのデータが返される.

ユーザーが新しいツイートを投稿するには POST statuses/update のエンドポイントを利用する. POST statuses/update には,ツイートの文章や,リプライの場合はリプライ先のツイートの ID などのデータを送信する. また,ツイートに画像データを添付したい場合は, POST media/upload を併せて使用する. ツイートの削除を行うには, POST statuses/destroy/:id を用いる.

そのほか,頻繁に行われる操作としては, POST statuses/retweet/:idPOST statuses/unretweet/:id がある. これらは, :id で指定されるツイートに対して,それぞれリツイートを実行あるいは取り消すための API である. また, POST favorites/createPOST favorites/destroy を使用することによって,選択されたツイートに"いいね"を追加したり,取り消したりする操作を行う.

このような一連の操作が, Twitter のアプリの背後では行われている. また,自分自身でボットを作成したい場合は,これらの API を適切に組み合わせ,カスタムのプログラムを書くことで実現される.

このように, API はあらゆるウェブサービスを作るうえで一番基礎となる要素である. 次からの章では本章で紹介した用語が何度も出てくるので,頭の片隅に置いたうえで読み進めていただきたい.

]]>
<![CDATA[File Name Conventions ]]> https://note.toshiki.dev/development/file-naming-convention https://note.toshiki.dev/development/file-naming-convention Thu, 01 Jul 2021 00:00:00 GMT File Name Conventions

A collection of guidelines for writing file names used in web projects.

Possible characters

Use dashes as delimiters

  • You should use dashes (-) as delimiters.
  • Periods are allowed in some cases, such as for languages and conditions.
  • Never use spaces or underscores. Spaces are converted to %20 in URLs or can break an URL when shared. Underscores are difficult to see when the file name is displayed as an underlined link. Although the use of underscores does not impact your ranking that much, Google advices not to use underscores.
  • Exceptions apply for functional requirements, such as for Sass partials. A leading underscore informs the Sass compiler a file is only a partial file and should never be generated into a stand alone CSS file.

Right:

file-name-with-dashes.en.min.html
file-name-with-dashes.en.min.html

Do not use special characters

Avoid using non-alphanumeric characters in file names, such as: '*' ':' '\' '/' '<' '>' '|' '"' '!' '?' '[' ']' ';' '=' '+' '&' '£' '$' '' '%' or ','. These characters can have special meaning in programming languages or can cause problems with different operating systems.

Use lowercase, never uppercase

We should always consider URLs as case-sensitive according to W3.org. Therefore, use lowercase to reduces errors when typing URLs.

Write sections of a file name in a consistent order

Sections should be written in this order:

  1. Description
  2. Number
  3. Date
  4. Target device, image size, pixel density
  5. Version number
  6. Status
  7. Language code
  8. File conditions

Possible combinations

description-01-20150102-palm-1.0b-draft.en.min.js /* extreme combination */
description.min.js
description.en.html
description-01.jpg
description-02.jpg
description-1024x768_2x.jpg
description-desk_2x.jpg
description-01-20150102-palm-1.0b-draft.en.min.js /* extreme combination */
description.min.js
description.en.html
description-01.jpg
description-02.jpg
description-1024x768_2x.jpg
description-desk_2x.jpg

Write description for developers and users

Don't be afraid to write long informative file names. Few people type a file name manually and most operating systems support 255 characters. But only add information that makes it easy for users and developers to recognize files from one another at a glance. For the description use information such as:

  • type of data
  • project name or acronym
  • subjects
  • people's names
  • characteristics
  • location

Give your images detailed, informative filenames The filename can give Google clues about the subject matter of the image. Try to make your filename a good description of the subject matter of the image. For example, my-new-black-kitten.jpg is a lot more informative than IMG00023.JPG. Descriptive filenames can also be useful to users: If we're unable to find suitable text in the page on which we found the image, we'll use the filename as the image's snippet in our search results. - Google, 2015, Image publishing guidelines

Keep people's names compact

Sometimes you want to include the name of a person in the file name, e.g. the author or the person in the photo.

  • Write names without word delimiters.
  • Only write initials for the first name and write the last name in full. There are two exceptions: (1) when the last name or final file name is very long you may use initials for the last name; (2) when there is already a person with the same combination, you may write the first name in full.
  • If people have exactly the same name written in full, you can add a number: firstnamelastname2.

Right:

bvandebiezen.jpg
shoogenhout.jpg
a-very-long-description-with-name-bvdb.jpg
asmith.jpg
adamsmith.jpg
adamsmith2.jpg
bvandebiezen.jpg
shoogenhout.jpg
a-very-long-description-with-name-bvdb.jpg
asmith.jpg
adamsmith.jpg
adamsmith2.jpg

Use two or more digits to distinguish sequential files with the same description

  • Start number with a dash as a delimiter.
  • Add a zero to single digit numbers, e.g. '01' instead of '1'.
  • Numbers may also be placed before the description if needed. A dash will still be used as delimiter with the description.

Right:

description-01.jpg
description-02.jpg
description-03.jpg
description-04.jpg

01-description.jpg
02-description.jpg
03-description.jpg
04-description.jpg
description-01.jpg
description-02.jpg
description-03.jpg
description-04.jpg

01-description.jpg
02-description.jpg
03-description.jpg
04-description.jpg

Keep dates or date ranges compact and start with year

  • Write dates without delimiters.
  • Always use four digits for years, two digits for months and two digits for days.
  • Start with year, then month, and end with day if available: yyyymmdd, yyyymm, or yyyy. This makes sure similar file names are sorted by date when sorted alphabetically.
  • Use a double dash to separate two dates describing an interval: yyyy--yyyy. Start with the earliest date.

Right:

description-20150401.php
description-201504.php
description-2015.php
description-2000--2010.php
description-20150401.php
description-201504.php
description-2015.php
description-2000--2010.php

See 'ISO 8601' for further reading.

Use special modifiers for target devices, image sizes or media queries, and pixel densities.

Modifiers are inspired by Apple iOS naming conventions. There are some differences. Apple uses '@'as a delimiter for the section indicating higher resolution images, for example '@2x' for retina images. Because '@' is a reserved character and can create problems, we use Bourbon's convention: an underscore. Also, Apple uses a tilde (~) as a delimiter for a section indicating specific devices. Because also a tilde can create problems, we suggest to simply use a dash.

  • Order should be: (1) target device or media query, (2) size, (3) pixel density.
  • Start target device or media queries with a dash (-) as delimiter.
  • Start image sizes with a dash (-) as delimiter.
  • Start pixel density with an underscore (_) as delimiter, for example '_2x' or '_3x'.
  • When only a width or height is available or applicable, add a 'w' for width or 'h' for height directly after the the amount of pixels.
  • When both measurements are available, do not add a 'w' or 'h' and separate the width and height with an 'x'.
  • When both the width and height should not exceed a dimension but the images should keep the original aspect ratio, add a 'max' (maximum) after the amount of pixels.

Right:

description_2x.jpg
description-lap.jpg
description-desk.jpg
description-lap_2x.jpg
description-palm-1024w_2x.jpg
description-iphone5-568h_2x.jpg
description-palm-1024x768_2x.jpg
description-40max.jpg
description_2x.jpg
description-lap.jpg
description-desk.jpg
description-lap_2x.jpg
description-palm-1024w_2x.jpg
description-iphone5-568h_2x.jpg
description-palm-1024x768_2x.jpg
description-40max.jpg

Use version numbers if available

  • Start version with a dash (-) as delimiter.
  • Use periods (.) to separate point releases.
  • Always add trailing zeros to major releases, e.g. '2.0' instead of '2'.
  • Types, such as 'a' (alpha), 'b' (beta), 'rc1' (release candidate 1) can be added without delimiters.

Right:

description-0.5.js
description-1.0b.js
description-1.0rc1.js
description-0.5.js
description-1.0b.js
description-1.0rc1.js

Add status when needed

  • You can optionally add a file status such as 'draft' and 'published'.
  • Start status with a dash.

Right:

description-draft.md
description-draft.md

Add language code only when different languages are available

  • Use a period to separate the language code from the rest of the file name.
  • Use ISO 639-1, two-letter codes, for languages.
  • Only add languages when different languages are available.

Right:

description.nl.txt
description.en.txt
description.nl.txt
description.en.txt

Add file conditions just before the file extension

  • The file condition should be the last part, just before the file extension.
  • Use a period (.) to separate the condition from the rest of the file name.
  • Use periods (.) as a delimiter for different conditions.

Right:

description.min.js
description.custom1234.min.js
description.min.js
description.custom1234.min.js

Rewrite original file names not following conventions

It is not preferred to keep file names in it's original format if it doesn't match your file name conventions. But in some cases it is easier to keep the file name untouched. Sometimes you want to easily replace a file with a newer one from the original source in the future.

]]>
File Name Conventions

A collection of guidelines for writing file names used in web projects.

Possible characters

Use dashes as delimiters

  • You should use dashes (-) as delimiters.
  • Periods are allowed in some cases, such as for languages and conditions.
  • Never use spaces or underscores. Spaces are converted to %20 in URLs or can break an URL when shared. Underscores are difficult to see when the file name is displayed as an underlined link. Although the use of underscores does not impact your ranking that much, Google advices not to use underscores.
  • Exceptions apply for functional requirements, such as for Sass partials. A leading underscore informs the Sass compiler a file is only a partial file and should never be generated into a stand alone CSS file.

Right:

file-name-with-dashes.en.min.html
file-name-with-dashes.en.min.html

Do not use special characters

Avoid using non-alphanumeric characters in file names, such as: '*' ':' '\' '/' '<' '>' '|' '"' '!' '?' '[' ']' ';' '=' '+' '&' '£' '$' '' '%' or ','. These characters can have special meaning in programming languages or can cause problems with different operating systems.

Use lowercase, never uppercase

We should always consider URLs as case-sensitive according to W3.org. Therefore, use lowercase to reduces errors when typing URLs.

Write sections of a file name in a consistent order

Sections should be written in this order:

  1. Description
  2. Number
  3. Date
  4. Target device, image size, pixel density
  5. Version number
  6. Status
  7. Language code
  8. File conditions

Possible combinations

description-01-20150102-palm-1.0b-draft.en.min.js /* extreme combination */
description.min.js
description.en.html
description-01.jpg
description-02.jpg
description-1024x768_2x.jpg
description-desk_2x.jpg
description-01-20150102-palm-1.0b-draft.en.min.js /* extreme combination */
description.min.js
description.en.html
description-01.jpg
description-02.jpg
description-1024x768_2x.jpg
description-desk_2x.jpg

Write description for developers and users

Don't be afraid to write long informative file names. Few people type a file name manually and most operating systems support 255 characters. But only add information that makes it easy for users and developers to recognize files from one another at a glance. For the description use information such as:

  • type of data
  • project name or acronym
  • subjects
  • people's names
  • characteristics
  • location

Give your images detailed, informative filenames The filename can give Google clues about the subject matter of the image. Try to make your filename a good description of the subject matter of the image. For example, my-new-black-kitten.jpg is a lot more informative than IMG00023.JPG. Descriptive filenames can also be useful to users: If we're unable to find suitable text in the page on which we found the image, we'll use the filename as the image's snippet in our search results. - Google, 2015, Image publishing guidelines

Keep people's names compact

Sometimes you want to include the name of a person in the file name, e.g. the author or the person in the photo.

  • Write names without word delimiters.
  • Only write initials for the first name and write the last name in full. There are two exceptions: (1) when the last name or final file name is very long you may use initials for the last name; (2) when there is already a person with the same combination, you may write the first name in full.
  • If people have exactly the same name written in full, you can add a number: firstnamelastname2.

Right:

bvandebiezen.jpg
shoogenhout.jpg
a-very-long-description-with-name-bvdb.jpg
asmith.jpg
adamsmith.jpg
adamsmith2.jpg
bvandebiezen.jpg
shoogenhout.jpg
a-very-long-description-with-name-bvdb.jpg
asmith.jpg
adamsmith.jpg
adamsmith2.jpg

Use two or more digits to distinguish sequential files with the same description

  • Start number with a dash as a delimiter.
  • Add a zero to single digit numbers, e.g. '01' instead of '1'.
  • Numbers may also be placed before the description if needed. A dash will still be used as delimiter with the description.

Right:

description-01.jpg
description-02.jpg
description-03.jpg
description-04.jpg

01-description.jpg
02-description.jpg
03-description.jpg
04-description.jpg
description-01.jpg
description-02.jpg
description-03.jpg
description-04.jpg

01-description.jpg
02-description.jpg
03-description.jpg
04-description.jpg

Keep dates or date ranges compact and start with year

  • Write dates without delimiters.
  • Always use four digits for years, two digits for months and two digits for days.
  • Start with year, then month, and end with day if available: yyyymmdd, yyyymm, or yyyy. This makes sure similar file names are sorted by date when sorted alphabetically.
  • Use a double dash to separate two dates describing an interval: yyyy--yyyy. Start with the earliest date.

Right:

description-20150401.php
description-201504.php
description-2015.php
description-2000--2010.php
description-20150401.php
description-201504.php
description-2015.php
description-2000--2010.php

See 'ISO 8601' for further reading.

Use special modifiers for target devices, image sizes or media queries, and pixel densities.

Modifiers are inspired by Apple iOS naming conventions. There are some differences. Apple uses '@'as a delimiter for the section indicating higher resolution images, for example '@2x' for retina images. Because '@' is a reserved character and can create problems, we use Bourbon's convention: an underscore. Also, Apple uses a tilde (~) as a delimiter for a section indicating specific devices. Because also a tilde can create problems, we suggest to simply use a dash.

  • Order should be: (1) target device or media query, (2) size, (3) pixel density.
  • Start target device or media queries with a dash (-) as delimiter.
  • Start image sizes with a dash (-) as delimiter.
  • Start pixel density with an underscore (_) as delimiter, for example '_2x' or '_3x'.
  • When only a width or height is available or applicable, add a 'w' for width or 'h' for height directly after the the amount of pixels.
  • When both measurements are available, do not add a 'w' or 'h' and separate the width and height with an 'x'.
  • When both the width and height should not exceed a dimension but the images should keep the original aspect ratio, add a 'max' (maximum) after the amount of pixels.

Right:

description_2x.jpg
description-lap.jpg
description-desk.jpg
description-lap_2x.jpg
description-palm-1024w_2x.jpg
description-iphone5-568h_2x.jpg
description-palm-1024x768_2x.jpg
description-40max.jpg
description_2x.jpg
description-lap.jpg
description-desk.jpg
description-lap_2x.jpg
description-palm-1024w_2x.jpg
description-iphone5-568h_2x.jpg
description-palm-1024x768_2x.jpg
description-40max.jpg

Use version numbers if available

  • Start version with a dash (-) as delimiter.
  • Use periods (.) to separate point releases.
  • Always add trailing zeros to major releases, e.g. '2.0' instead of '2'.
  • Types, such as 'a' (alpha), 'b' (beta), 'rc1' (release candidate 1) can be added without delimiters.

Right:

description-0.5.js
description-1.0b.js
description-1.0rc1.js
description-0.5.js
description-1.0b.js
description-1.0rc1.js

Add status when needed

  • You can optionally add a file status such as 'draft' and 'published'.
  • Start status with a dash.

Right:

description-draft.md
description-draft.md

Add language code only when different languages are available

  • Use a period to separate the language code from the rest of the file name.
  • Use ISO 639-1, two-letter codes, for languages.
  • Only add languages when different languages are available.

Right:

description.nl.txt
description.en.txt
description.nl.txt
description.en.txt

Add file conditions just before the file extension

  • The file condition should be the last part, just before the file extension.
  • Use a period (.) to separate the condition from the rest of the file name.
  • Use periods (.) as a delimiter for different conditions.

Right:

description.min.js
description.custom1234.min.js
description.min.js
description.custom1234.min.js

Rewrite original file names not following conventions

It is not preferred to keep file names in it's original format if it doesn't match your file name conventions. But in some cases it is easier to keep the file name untouched. Sometimes you want to easily replace a file with a newer one from the original source in the future.

]]>
<![CDATA[Git push results in "Authentication Failed”]]> https://note.toshiki.dev/development/git-push-authentication-failed https://note.toshiki.dev/development/git-push-authentication-failed Thu, 01 Jul 2021 00:00:00 GMT Git push results in "Authentication Failed”

Issue

bash
$ git push
Username for 'https://github.com': ${{ GITHUB_USERNAME }}
Password for 'https://andatoshiki@github.com': ${{ GITHUB_PASSWORD }} # or GitHub personal access token
remote: Invalid username or password.
fatal: Authentication failed for 'https://github.com/andatoshiki/andatoshiki.git/'
$ git push
Username for 'https://github.com': ${{ GITHUB_USERNAME }}
Password for 'https://andatoshiki@github.com': ${{ GITHUB_PASSWORD }} # or GitHub personal access token
remote: Invalid username or password.
fatal: Authentication failed for 'https://github.com/andatoshiki/andatoshiki.git/'

git push to GitHub remote branch failed via https protocol

Solution

Solution 1

If you enabled two-factor authentication in your GitHub account you won't be able to push via HTTPS using your accounts password. Instead you need to generate a personal access token. This can be done in the application settings of your GitHub account. Using this token as your password should allow you to push to your remote repository via HTTPS. Use your username as usual.

You may also need to update the origin for your repository if it is set to HTTPS. Do this to switch to SSH:

bash
$ git remote -v
$ git remote set-url origin git@github.com:$USERNAME/$REPONAME.git
$ git remote -v
$ git remote set-url origin git@github.com:$USERNAME/$REPONAME.git

Solution 2

GitHub username & password/access token mismatched due to prior temporary Git config setup → Reset Git global username & email config or in current repository

To set your global username/email configuration:

  1. Open the command line.
  2. Set your username: git config --global user.name "FIRST_NAME LAST_NAME"
  3. Set your email address: git config --global user.email "MY_NAME@example.com"

To set repository-specific username/email configuration:

  1. From the command line, change into the repository directory.
  2. Set your username: git config user.name "FIRST_NAME LAST_NAME"
  3. Set your email address: git config user.email "MY_NAME@example.com"
  4. Verify your configuration by displaying your configuration file: cat .git/config
]]>
Git push results in "Authentication Failed”

Issue

bash
$ git push
Username for 'https://github.com': ${{ GITHUB_USERNAME }}
Password for 'https://andatoshiki@github.com': ${{ GITHUB_PASSWORD }} # or GitHub personal access token
remote: Invalid username or password.
fatal: Authentication failed for 'https://github.com/andatoshiki/andatoshiki.git/'
$ git push
Username for 'https://github.com': ${{ GITHUB_USERNAME }}
Password for 'https://andatoshiki@github.com': ${{ GITHUB_PASSWORD }} # or GitHub personal access token
remote: Invalid username or password.
fatal: Authentication failed for 'https://github.com/andatoshiki/andatoshiki.git/'

git push to GitHub remote branch failed via https protocol

Solution

Solution 1

If you enabled two-factor authentication in your GitHub account you won't be able to push via HTTPS using your accounts password. Instead you need to generate a personal access token. This can be done in the application settings of your GitHub account. Using this token as your password should allow you to push to your remote repository via HTTPS. Use your username as usual.

You may also need to update the origin for your repository if it is set to HTTPS. Do this to switch to SSH:

bash
$ git remote -v
$ git remote set-url origin git@github.com:$USERNAME/$REPONAME.git
$ git remote -v
$ git remote set-url origin git@github.com:$USERNAME/$REPONAME.git

Solution 2

GitHub username & password/access token mismatched due to prior temporary Git config setup → Reset Git global username & email config or in current repository

To set your global username/email configuration:

  1. Open the command line.
  2. Set your username: git config --global user.name "FIRST_NAME LAST_NAME"
  3. Set your email address: git config --global user.email "MY_NAME@example.com"

To set repository-specific username/email configuration:

  1. From the command line, change into the repository directory.
  2. Set your username: git config user.name "FIRST_NAME LAST_NAME"
  3. Set your email address: git config user.email "MY_NAME@example.com"
  4. Verify your configuration by displaying your configuration file: cat .git/config
]]>
<![CDATA[Installing NPM Packages Behind Proxy ]]> https://note.toshiki.dev/development/installing-npm-package-behind-proxy https://note.toshiki.dev/development/installing-npm-package-behind-proxy Thu, 01 Jul 2021 00:00:00 GMT Installing NPM Packages Behind Proxy

On a recent assignment, I needed to install npm behind a corporate proxy. I had already set the environment variables HTTP_PROXY and HTTPS_PROXY. Other command line utilities, like ruby gems, recognized these environment variables. Npm did not.

After some googling, I found the following way to configure the proxy for npm.

bash
# npm
npm config set proxy <http://127.0.0.1:7890>
npm config set https-proxy <http://127.0.0.1:7890>

# yarn
yarn config set proxy <http://127.0.0.1:7890>
yarn config set https-proxy <http://127.0.0.1:7890>
# npm
npm config set proxy <http://127.0.0.1:7890>
npm config set https-proxy <http://127.0.0.1:7890>

# yarn
yarn config set proxy <http://127.0.0.1:7890>
yarn config set https-proxy <http://127.0.0.1:7890>

If you need to specify credentials, they can be passed in the url using the following syntax.

[<http://user_name:password@proxy.company.com:8080>](<http://user_name:password@proxy.company.com:8080/>)
[<http://user_name:password@proxy.company.com:8080>](<http://user_name:password@proxy.company.com:8080/>)

Further exploration of the npm config documentation showed that the npm config set command sets the proxy configuration in your .npmrc file. You can also set the proxy configuration as a command line argument or environment variable.

Configuration parameters can be specified using -- when executing npm. So the proxy could also be specified as follows.

bash
npm --https-proxy=http://proxy.company.com:8080 -g install karma
npm --https-proxy=http://proxy.company.com:8080 -g install karma

To pass configurattion parameters to npm as environment variables, they must be prefixed with npm_config_. The proxy configuration could be set with environment variables as follows.

bash
export npm_config_proxy <http://proxy.company.com:8080>
export npm_config_https_proxy <http://proxy.company.com:8080>
export npm_config_proxy <http://proxy.company.com:8080>
export npm_config_https_proxy <http://proxy.company.com:8080>
]]>
Installing NPM Packages Behind Proxy

On a recent assignment, I needed to install npm behind a corporate proxy. I had already set the environment variables HTTP_PROXY and HTTPS_PROXY. Other command line utilities, like ruby gems, recognized these environment variables. Npm did not.

After some googling, I found the following way to configure the proxy for npm.

bash
# npm
npm config set proxy <http://127.0.0.1:7890>
npm config set https-proxy <http://127.0.0.1:7890>

# yarn
yarn config set proxy <http://127.0.0.1:7890>
yarn config set https-proxy <http://127.0.0.1:7890>
# npm
npm config set proxy <http://127.0.0.1:7890>
npm config set https-proxy <http://127.0.0.1:7890>

# yarn
yarn config set proxy <http://127.0.0.1:7890>
yarn config set https-proxy <http://127.0.0.1:7890>

If you need to specify credentials, they can be passed in the url using the following syntax.

[<http://user_name:password@proxy.company.com:8080>](<http://user_name:password@proxy.company.com:8080/>)
[<http://user_name:password@proxy.company.com:8080>](<http://user_name:password@proxy.company.com:8080/>)

Further exploration of the npm config documentation showed that the npm config set command sets the proxy configuration in your .npmrc file. You can also set the proxy configuration as a command line argument or environment variable.

Configuration parameters can be specified using -- when executing npm. So the proxy could also be specified as follows.

bash
npm --https-proxy=http://proxy.company.com:8080 -g install karma
npm --https-proxy=http://proxy.company.com:8080 -g install karma

To pass configurattion parameters to npm as environment variables, they must be prefixed with npm_config_. The proxy configuration could be set with environment variables as follows.

bash
export npm_config_proxy <http://proxy.company.com:8080>
export npm_config_https_proxy <http://proxy.company.com:8080>
export npm_config_proxy <http://proxy.company.com:8080>
export npm_config_https_proxy <http://proxy.company.com:8080>
]]>
<![CDATA[Proxies Configuration for Shells & Terminal]]> https://note.toshiki.dev/development/proxy4shell-terminal https://note.toshiki.dev/development/proxy4shell-terminal Thu, 02 Nov 2023 00:00:00 GMT Proxies Configuration for Shells & Terminal

TL;DR

This article discusses the configuration of proxies for shells and terminals. It explains the advantages of using proxy servers to bypass network restrictions and surveillance. The article provides examples of the challenges faced when accessing foreign services and shows how to set up a proxy tunnel using the curl command. It also provides scripts and instructions for setting up proxy switches in different shell environments, such as zsh, bash, and Windows CMD and PowerShell. The article concludes with additional information on proxy configurations for applications like ssh and tips for working with authentication procedures.

1. Background

Proxies or namely proxy servers are by far one of the most affordable or cost-effective option to establish a masked layer connection to bypass the network restrictions with the annoying surveillance tracked by a local network ISP as compared to a click-to-use VPN service, which generically requires more individual invest to protect themselves under the insecure internet environment nowadays. When a user resides within the environment where the local gateways of full, user-dominant open access towards the internet is censored or restricted with domestic network blockages by the country.

while I adopt absolute subjective yet objective perspectives on the individual viewpoints towards the MIIT department of each country those of which applies the internet regulatory services within the national range for avoiding pitfalls on misleading information brought by cross-border influences; meanwhile regardlessly such measures are still facing controversial debates amongst publics that vastly limits the independent freedom rights, though advantages must not be underestimated, still.

2. The Major Issue

The majority of the issue still heavily preserves across the developmental fields which the layer of the blockage imposes limits on communicating with third-party, remote platforms such as Github or registries like NPM for frontend developments that stores key packages or components, as a requirement during a pre-built phase of a project. Most of the time foreign services becomes completely inaccessible or fortunately users could reach the services during a possible ISP maintenance downtime but normally the potentiality is mere, or hardly none yet the load speed before TTL connection expires are objectively slow, shortly before the origin site DNS being spoofed again. The unpleasant experiences with the networking somewhat affects interest on development reduces by high percentages or it even strand some awesome projects ran ashore ultimately.

The following screenshots are a more direct representation to visualize the differences between the connection towards one of the most beloved search engine, Google with the following command via curl.

sh
curl -I google.com
curl -I google.com

The command is used to fetch the headers of a URL or web page. When you run "curl -I" followed by a URL, the command sends an HTTP HEAD request to the specified URL and retrieves the HTTP headers of the response. This allows you to view the information contained in the response headers without requesting and downloading the entire content of the page. The headers typically include details like the server information, content type, content length, status codes, and more.

The following screenshot from terminal indicates the the final output of the package availability received without losses on a bare unmasked network environment, which returns FAIL in the final connection after a dry run fails 11s after when the TTL expires the connection fails.

The next screenshot from terminal indicates a temporary proxy tunnel is established both in http and https protocol tunneled through a local proxy gateway at the local systemic IP address at 127.0.0.1 and exposes the proxy server at a mix of socks/https/http protocol port at 7890, just simply with the traditional export method by setting up in the nonce, the command is given as followed.

sh
export http_proxy=http://127.0.0.1:7890
export https_proxy=$http_proxy
export http_proxy=http://127.0.0.1:7890
export https_proxy=$http_proxy

And then we re-enter the same command with curl from above; surprisingly, the header responses returned TTP/1.1 200 OK, thus the conclusion drawn here is the proxy server we launched was successfully up and running with tunneled access towards foreign sites without restrictions! Hooray!

◎ Curl in action with successful response header from Google

Since each proxy configuration might varies atop of the user preferred client, not including ShadowRocket, Clash, V2ray or other proprietary softwares that are licensed either behind a paywall to run with; or simply expensive to purchase a subscription; the proxy ports forwarded varies alongside the changes amongst clients. But the overall approach taken into the account still remains the same with the following traditional formats, the local IP of the machine (normally 127.0.0.1) followed after with the specified ports. In the scenario of the article is referenced as example, I chose Clash (in spite the entire Clash project repository as well as its affiliated forked projects are being taken down by anonymous reasons by either archiving the overall projects or simply shutting down due to possible legal actions or political reasons regarding the country of residency of various developers).

sh
# http protocal
http://127.0.0.1:7890
# https protocal
https://127.0.0.1:7890
# http protocal
http://127.0.0.1:7890
# https protocal
https://127.0.0.1:7890

2.1: Kill the Complexities; Unleash the Simplicity!

But, the logic routes to the central question on: How can we simplify the course of action on setting up proxies without manually run export command every single time we wish to use? Below is a simple approach by aliasing a shortcut code to a proxy switch script amended towards your shell configuration profile that initializes on every session startups, in this case I uses zsh since it's integrated as the default shell on macOS since the release of macOS Catalina, yet it's one of my most familiar and favored shell when was using other OS as well.

Though some people might use autosuggestion extensions as third-party shell features to automatically predict the command completion after a code piece is inputted such as zsh-autosuggestion plugin or fan of fish shell users has the native privilege of auto completions but I personally not fond of such featured integration since it might decelerate the load speed of an active session; I prefer stick tightly with original shell.

sh
# open your shell profile with an preferred editor
$ vim ~/.zshrc

# session proxy switch shortcut
function proxy_on() {
    export http_proxy=http://127.0.0.1:7890
    export https_proxy=$http_proxy
    echo -e "global proxy for the current terminal session has turned on"
}

function proxy_off() {
    unset http_proxy https_proxy
    echo -e "global proxy for the current terminal session has turned off"
}

# restart your terminal with a new session or reload the config
$ source ~/.zshrc
# open your shell profile with an preferred editor
$ vim ~/.zshrc

# session proxy switch shortcut
function proxy_on() {
    export http_proxy=http://127.0.0.1:7890
    export https_proxy=$http_proxy
    echo -e "global proxy for the current terminal session has turned on"
}

function proxy_off() {
    unset http_proxy https_proxy
    echo -e "global proxy for the current terminal session has turned off"
}

# restart your terminal with a new session or reload the config
$ source ~/.zshrc

The proxy essentially provides two shortcut command function defined with proxy_on and proxy_off. he proxy_on function sets the environment variables http_proxy and https_proxy to http://127.0.0.1:7890, which is the default proxy port of the traditional clash protocol, here is where you could replace the IP with other remote proxy servers or ports of other local proxies .Enabling a global proxy for the current terminal session. Meanwhile the proxy_off function unsets (removes) the http_proxy and https_proxy environment variables, effectively turning off the global proxy for the current terminal session. When any of the both executed, the indicator message will be echoed on the terminal, see the following screenshot in action.

◎ Enabling the shell session proxy with script

After you reload your shell profile you can test out the scripted command yourself. To test whether the proxy has a successful setup after the proxy has been switched on, run echo $http_proxy or https_proxy with a dollar sign in front of the alias as an indicator for environmental variable, the third command as shown in the screenshot above, the command will simply print the configured variable value addressed to the specified alias. Contrarily, if your terminal returns the following resultant,

sh
$ proxy_on
zsh: command not found: proxy_on
$ proxy_on
zsh: command not found: proxy_on

Then you will have to distinguish the exact shell you are currently on, the hereinafter content are mainly targeted towards novice learners whom are unable to track the shell types or configuration on particular operating systems. The configuration file for each shell varies their file names as well the location of storage; while Mac users could directly apply changes based on the instruction provided above if your system if Catalina or above. To know what exactly the active shell running, run,

sh
$ echo $SHELL
$ echo $SHELL

The returned string text will be the name of the current active shell, the following is a list of the possible shell profile config name affiliated with each shell; most of the config profile files should be lied under the ~ or the root/home folder of each operating system with a dot in front of the file names are inferred as hidden file or directory in most of the Unix-like systems, such as macOS, Ubuntu, Debian and etc, but some of the config file such as fish shell could locate in an isolated config directory. The usual format of a config file is as followed,

shell
~/.zshrc
~/.zshrc

The following is a list of the most common shells with their possible profile file names that corresponded,

  • /bin/bash : .bash_profile or .bashrc
  • /bin/zsh : .zprofile or .zshrc
  • /bin/fish: ~/.config/fish/config

Still, the location might still varies, users might have to perform individual research to precisely locate their configuration file location, which is out of my jurisdiction of concerns (it's just evident action of procrastination and laziness, my apologies if none of the ones above fits your demand) ;).

For Unix-like users, after you have specified your shell as well as your config file name and locations, copy the following code chunk as command and paste it back into your terminal and run to apply permanent changes to the configuration.

sh
cat >> ~/.zshrc << EOF
# session proxy switch shortcut
function proxy_on() {
    export http_proxy=http://127.0.0.1:7890
    export https_proxy=$http_proxy
    echo -e "global proxy for the current terminal session has turned on"
}

function proxy_off(){
    unset http_proxy https_proxy
    echo -e "global proxy for the current terminal session has turned off"
}
EOF
cat >> ~/.zshrc << EOF
# session proxy switch shortcut
function proxy_on() {
    export http_proxy=http://127.0.0.1:7890
    export https_proxy=$http_proxy
    echo -e "global proxy for the current terminal session has turned on"
}

function proxy_off(){
    unset http_proxy https_proxy
    echo -e "global proxy for the current terminal session has turned off"
}
EOF

The script above will write-in and install the proxy switch script and save the the content to the very end of the file. As a kindly reminder, if your shell is not zsh make sure to replace the string after cat >> to the actual path of your profile as well as your proxy server IP and port to the actual functioning details to your own demand; then ultimately, don't for get to reinitialize the shell by close and reopen the terminal or simply sourcing the config,

sh
source ~/.zshrc
source ~/.zshrc

To check whether the proxy script has taken its effect to the current session, don't forget to rerun the same echo command indicated as above. And up until here, the script has been properly installed and operatable as a charm, if your's still does not take any effect, go through the process again and read carefully through the documentation.

3: To All Windows Users

The documentation above are mainly targeted towards macOS & Linux users, to setup local proxy with Windows machines there is a complete different approach if you are more comfortably working with Powershells and CMD, since I disused windows less and less frequently by the time I decided to upgrade my device to macOS; even if I did use Windows my primary choice of developmental environment is still Linux by the native support of WSL with enhanced Ubuntu version in a virtual environment; the following commands are only done from my prior researches, I do not fully guarantee the usability of the commands, please use them at your own risks if any unexpected errors not only including system crashes or other affiliated damages, I do not relate responsibility to any of those presented.

Simple concluding, abandon proprietary software, fall in the hug of open source; Linux even if most of the users might feel overwhelming when getting started with the system first :). Alright, enough with off-topic talkings, let's jump right in the process.

3.1: CMD

cmd
set http_proxy=http://127.0.0.1:7890
set https_proxy=http://127.0.0.1:7890
set http_proxy=http://127.0.0.1:7890
set https_proxy=http://127.0.0.1:7890

The commands are basically the same to Unix but the major difference is the amend commands in Windows are set instead of export. Once again I haven't personally tested the command, thus only use them as a reference. And whenever you wish to unset the global proxy for the session just simply run the set proxy command again but without any proxy server details.

cmd
set http_proxy=
set https_proxy=
set http_proxy=
set https_proxy=

3.2: PowerShell

Alike CMD, the string after are exactly the same but the setup prefix command differentiates,

powershell
$env:http_proxy="http://127.0.0.1:1080"
$env:https_proxy="http://127.0.0.1:1080"
$env:http_proxy="http://127.0.0.1:1080"
$env:https_proxy="http://127.0.0.1:1080"

And to revert to the default proxy setting, execute the following command to unset both the http and https proxy.

powershell
$env:http_proxy=""
$env:https_proxy=""
$env:http_proxy=""
$env:https_proxy=""

4: Extended Trivia on Proxy

Sometimes a proxy server may require an authentication procedure involving passcode for accessing before establishing a secure connection to interact with the server itself. From the partial article above we only discussed on a simple local proxy server setup including a host IP with its forwarded port gateways; but when facing the scenario described for a net connection, we will need a bit more complex method when working in the CLI environment.

Before we start, quoting from one of the answer from AskUbuntu, resolving the misconception on the difference between terminal application and the net utilities falls underly,

Terminal is not net application. Maybe is better to say, in your case, terminal is container for net application like ssh, telnet, lftp, wget, lynx ...

A terminal provides a command-line interface that allows users to send commands and receive responses from network applications, facilitating communication and control over a network connection. It acts as a mediator between the user and the network applications, enabling the user to send instructions and receive information, but not a proxy client.

Done with the technical talkings, now let's dive into the actual configuration process of the shell. Other than simply inputting a host IP and a port followed, the following formats are the default configuration for a proxy server with HTTP connection protocol, follow the exact same process as described based on your shell type, modify the fields with the following,

shell
export http_proxy=http://username:password@proxyhost:port/
export ftp_proxy=http://username:password@proxyhost:port/
export telnet_proxy=http://username:password@proxyhost:port/
export http_proxy=http://username:password@proxyhost:port/
export ftp_proxy=http://username:password@proxyhost:port/
export telnet_proxy=http://username:password@proxyhost:port/

Another approach suggested by the same user whom provided the answer on AskUbuntu for all Ubuntu users, edit the proxy configuration at the root of your machine as follows,

sh
sudo -H vim /etc/profile.d/proxy.sh
sudo -H vim /etc/profile.d/proxy.sh

And add the exported proxy members aligning the format as above, then save and reinitialize the environment, viola. The patches edited are mainly targeted for incorporating with wget, ftp, lftp, telnet in terminal.

When working with ssh instance over a proxy, a different approach has to be taken since SSH library does not natively support SOCKS5 client, user will have to pass a ProxyCommand option as a workaround to apply proxied connection, below is an instance of socat,

sh
ssh -o ProxyCommand='socat - SOCKS4A:myproxy:%h:%p,socksuser=nobody' user@host
ssh -o ProxyCommand='socat - SOCKS4A:myproxy:%h:%p,socksuser=nobody' user@host

The proxyCommand option allows user to integrate socat as an intermediary mediator to establish connection above a proxy. Other alternatives like tsocks are as well viable to transparently use SOCKS for TCP traffic, Exemplifying running SOCKS5 over socat2,

bash
ssh -o ProxyCommand='socat - "SOCKS5:%h:%p|tcp:myproxy:1080"' user@host
ssh -o ProxyCommand='socat - "SOCKS5:%h:%p|tcp:myproxy:1080"' user@host

Further, socat2 for HTTP Proxy CONNECT method,

bash
ssh -o ProxyCommand='socat - "PROXY:%h:%p|tcp:myproxy:80"' user@host
ssh -o ProxyCommand='socat - "PROXY:%h:%p|tcp:myproxy:80"' user@host
]]>
Proxies Configuration for Shells & Terminal

TL;DR

This article discusses the configuration of proxies for shells and terminals. It explains the advantages of using proxy servers to bypass network restrictions and surveillance. The article provides examples of the challenges faced when accessing foreign services and shows how to set up a proxy tunnel using the curl command. It also provides scripts and instructions for setting up proxy switches in different shell environments, such as zsh, bash, and Windows CMD and PowerShell. The article concludes with additional information on proxy configurations for applications like ssh and tips for working with authentication procedures.

1. Background

Proxies or namely proxy servers are by far one of the most affordable or cost-effective option to establish a masked layer connection to bypass the network restrictions with the annoying surveillance tracked by a local network ISP as compared to a click-to-use VPN service, which generically requires more individual invest to protect themselves under the insecure internet environment nowadays. When a user resides within the environment where the local gateways of full, user-dominant open access towards the internet is censored or restricted with domestic network blockages by the country.

while I adopt absolute subjective yet objective perspectives on the individual viewpoints towards the MIIT department of each country those of which applies the internet regulatory services within the national range for avoiding pitfalls on misleading information brought by cross-border influences; meanwhile regardlessly such measures are still facing controversial debates amongst publics that vastly limits the independent freedom rights, though advantages must not be underestimated, still.

2. The Major Issue

The majority of the issue still heavily preserves across the developmental fields which the layer of the blockage imposes limits on communicating with third-party, remote platforms such as Github or registries like NPM for frontend developments that stores key packages or components, as a requirement during a pre-built phase of a project. Most of the time foreign services becomes completely inaccessible or fortunately users could reach the services during a possible ISP maintenance downtime but normally the potentiality is mere, or hardly none yet the load speed before TTL connection expires are objectively slow, shortly before the origin site DNS being spoofed again. The unpleasant experiences with the networking somewhat affects interest on development reduces by high percentages or it even strand some awesome projects ran ashore ultimately.

The following screenshots are a more direct representation to visualize the differences between the connection towards one of the most beloved search engine, Google with the following command via curl.

sh
curl -I google.com
curl -I google.com

The command is used to fetch the headers of a URL or web page. When you run "curl -I" followed by a URL, the command sends an HTTP HEAD request to the specified URL and retrieves the HTTP headers of the response. This allows you to view the information contained in the response headers without requesting and downloading the entire content of the page. The headers typically include details like the server information, content type, content length, status codes, and more.

The following screenshot from terminal indicates the the final output of the package availability received without losses on a bare unmasked network environment, which returns FAIL in the final connection after a dry run fails 11s after when the TTL expires the connection fails.

The next screenshot from terminal indicates a temporary proxy tunnel is established both in http and https protocol tunneled through a local proxy gateway at the local systemic IP address at 127.0.0.1 and exposes the proxy server at a mix of socks/https/http protocol port at 7890, just simply with the traditional export method by setting up in the nonce, the command is given as followed.

sh
export http_proxy=http://127.0.0.1:7890
export https_proxy=$http_proxy
export http_proxy=http://127.0.0.1:7890
export https_proxy=$http_proxy

And then we re-enter the same command with curl from above; surprisingly, the header responses returned TTP/1.1 200 OK, thus the conclusion drawn here is the proxy server we launched was successfully up and running with tunneled access towards foreign sites without restrictions! Hooray!

◎ Curl in action with successful response header from Google

Since each proxy configuration might varies atop of the user preferred client, not including ShadowRocket, Clash, V2ray or other proprietary softwares that are licensed either behind a paywall to run with; or simply expensive to purchase a subscription; the proxy ports forwarded varies alongside the changes amongst clients. But the overall approach taken into the account still remains the same with the following traditional formats, the local IP of the machine (normally 127.0.0.1) followed after with the specified ports. In the scenario of the article is referenced as example, I chose Clash (in spite the entire Clash project repository as well as its affiliated forked projects are being taken down by anonymous reasons by either archiving the overall projects or simply shutting down due to possible legal actions or political reasons regarding the country of residency of various developers).

sh
# http protocal
http://127.0.0.1:7890
# https protocal
https://127.0.0.1:7890
# http protocal
http://127.0.0.1:7890
# https protocal
https://127.0.0.1:7890

2.1: Kill the Complexities; Unleash the Simplicity!

But, the logic routes to the central question on: How can we simplify the course of action on setting up proxies without manually run export command every single time we wish to use? Below is a simple approach by aliasing a shortcut code to a proxy switch script amended towards your shell configuration profile that initializes on every session startups, in this case I uses zsh since it's integrated as the default shell on macOS since the release of macOS Catalina, yet it's one of my most familiar and favored shell when was using other OS as well.

Though some people might use autosuggestion extensions as third-party shell features to automatically predict the command completion after a code piece is inputted such as zsh-autosuggestion plugin or fan of fish shell users has the native privilege of auto completions but I personally not fond of such featured integration since it might decelerate the load speed of an active session; I prefer stick tightly with original shell.

sh
# open your shell profile with an preferred editor
$ vim ~/.zshrc

# session proxy switch shortcut
function proxy_on() {
    export http_proxy=http://127.0.0.1:7890
    export https_proxy=$http_proxy
    echo -e "global proxy for the current terminal session has turned on"
}

function proxy_off() {
    unset http_proxy https_proxy
    echo -e "global proxy for the current terminal session has turned off"
}

# restart your terminal with a new session or reload the config
$ source ~/.zshrc
# open your shell profile with an preferred editor
$ vim ~/.zshrc

# session proxy switch shortcut
function proxy_on() {
    export http_proxy=http://127.0.0.1:7890
    export https_proxy=$http_proxy
    echo -e "global proxy for the current terminal session has turned on"
}

function proxy_off() {
    unset http_proxy https_proxy
    echo -e "global proxy for the current terminal session has turned off"
}

# restart your terminal with a new session or reload the config
$ source ~/.zshrc

The proxy essentially provides two shortcut command function defined with proxy_on and proxy_off. he proxy_on function sets the environment variables http_proxy and https_proxy to http://127.0.0.1:7890, which is the default proxy port of the traditional clash protocol, here is where you could replace the IP with other remote proxy servers or ports of other local proxies .Enabling a global proxy for the current terminal session. Meanwhile the proxy_off function unsets (removes) the http_proxy and https_proxy environment variables, effectively turning off the global proxy for the current terminal session. When any of the both executed, the indicator message will be echoed on the terminal, see the following screenshot in action.

◎ Enabling the shell session proxy with script

After you reload your shell profile you can test out the scripted command yourself. To test whether the proxy has a successful setup after the proxy has been switched on, run echo $http_proxy or https_proxy with a dollar sign in front of the alias as an indicator for environmental variable, the third command as shown in the screenshot above, the command will simply print the configured variable value addressed to the specified alias. Contrarily, if your terminal returns the following resultant,

sh
$ proxy_on
zsh: command not found: proxy_on
$ proxy_on
zsh: command not found: proxy_on

Then you will have to distinguish the exact shell you are currently on, the hereinafter content are mainly targeted towards novice learners whom are unable to track the shell types or configuration on particular operating systems. The configuration file for each shell varies their file names as well the location of storage; while Mac users could directly apply changes based on the instruction provided above if your system if Catalina or above. To know what exactly the active shell running, run,

sh
$ echo $SHELL
$ echo $SHELL

The returned string text will be the name of the current active shell, the following is a list of the possible shell profile config name affiliated with each shell; most of the config profile files should be lied under the ~ or the root/home folder of each operating system with a dot in front of the file names are inferred as hidden file or directory in most of the Unix-like systems, such as macOS, Ubuntu, Debian and etc, but some of the config file such as fish shell could locate in an isolated config directory. The usual format of a config file is as followed,

shell
~/.zshrc
~/.zshrc

The following is a list of the most common shells with their possible profile file names that corresponded,

  • /bin/bash : .bash_profile or .bashrc
  • /bin/zsh : .zprofile or .zshrc
  • /bin/fish: ~/.config/fish/config

Still, the location might still varies, users might have to perform individual research to precisely locate their configuration file location, which is out of my jurisdiction of concerns (it's just evident action of procrastination and laziness, my apologies if none of the ones above fits your demand) ;).

For Unix-like users, after you have specified your shell as well as your config file name and locations, copy the following code chunk as command and paste it back into your terminal and run to apply permanent changes to the configuration.

sh
cat >> ~/.zshrc << EOF
# session proxy switch shortcut
function proxy_on() {
    export http_proxy=http://127.0.0.1:7890
    export https_proxy=$http_proxy
    echo -e "global proxy for the current terminal session has turned on"
}

function proxy_off(){
    unset http_proxy https_proxy
    echo -e "global proxy for the current terminal session has turned off"
}
EOF
cat >> ~/.zshrc << EOF
# session proxy switch shortcut
function proxy_on() {
    export http_proxy=http://127.0.0.1:7890
    export https_proxy=$http_proxy
    echo -e "global proxy for the current terminal session has turned on"
}

function proxy_off(){
    unset http_proxy https_proxy
    echo -e "global proxy for the current terminal session has turned off"
}
EOF

The script above will write-in and install the proxy switch script and save the the content to the very end of the file. As a kindly reminder, if your shell is not zsh make sure to replace the string after cat >> to the actual path of your profile as well as your proxy server IP and port to the actual functioning details to your own demand; then ultimately, don't for get to reinitialize the shell by close and reopen the terminal or simply sourcing the config,

sh
source ~/.zshrc
source ~/.zshrc

To check whether the proxy script has taken its effect to the current session, don't forget to rerun the same echo command indicated as above. And up until here, the script has been properly installed and operatable as a charm, if your's still does not take any effect, go through the process again and read carefully through the documentation.

3: To All Windows Users

The documentation above are mainly targeted towards macOS & Linux users, to setup local proxy with Windows machines there is a complete different approach if you are more comfortably working with Powershells and CMD, since I disused windows less and less frequently by the time I decided to upgrade my device to macOS; even if I did use Windows my primary choice of developmental environment is still Linux by the native support of WSL with enhanced Ubuntu version in a virtual environment; the following commands are only done from my prior researches, I do not fully guarantee the usability of the commands, please use them at your own risks if any unexpected errors not only including system crashes or other affiliated damages, I do not relate responsibility to any of those presented.

Simple concluding, abandon proprietary software, fall in the hug of open source; Linux even if most of the users might feel overwhelming when getting started with the system first :). Alright, enough with off-topic talkings, let's jump right in the process.

3.1: CMD

cmd
set http_proxy=http://127.0.0.1:7890
set https_proxy=http://127.0.0.1:7890
set http_proxy=http://127.0.0.1:7890
set https_proxy=http://127.0.0.1:7890

The commands are basically the same to Unix but the major difference is the amend commands in Windows are set instead of export. Once again I haven't personally tested the command, thus only use them as a reference. And whenever you wish to unset the global proxy for the session just simply run the set proxy command again but without any proxy server details.

cmd
set http_proxy=
set https_proxy=
set http_proxy=
set https_proxy=

3.2: PowerShell

Alike CMD, the string after are exactly the same but the setup prefix command differentiates,

powershell
$env:http_proxy="http://127.0.0.1:1080"
$env:https_proxy="http://127.0.0.1:1080"
$env:http_proxy="http://127.0.0.1:1080"
$env:https_proxy="http://127.0.0.1:1080"

And to revert to the default proxy setting, execute the following command to unset both the http and https proxy.

powershell
$env:http_proxy=""
$env:https_proxy=""
$env:http_proxy=""
$env:https_proxy=""

4: Extended Trivia on Proxy

Sometimes a proxy server may require an authentication procedure involving passcode for accessing before establishing a secure connection to interact with the server itself. From the partial article above we only discussed on a simple local proxy server setup including a host IP with its forwarded port gateways; but when facing the scenario described for a net connection, we will need a bit more complex method when working in the CLI environment.

Before we start, quoting from one of the answer from AskUbuntu, resolving the misconception on the difference between terminal application and the net utilities falls underly,

Terminal is not net application. Maybe is better to say, in your case, terminal is container for net application like ssh, telnet, lftp, wget, lynx ...

A terminal provides a command-line interface that allows users to send commands and receive responses from network applications, facilitating communication and control over a network connection. It acts as a mediator between the user and the network applications, enabling the user to send instructions and receive information, but not a proxy client.

Done with the technical talkings, now let's dive into the actual configuration process of the shell. Other than simply inputting a host IP and a port followed, the following formats are the default configuration for a proxy server with HTTP connection protocol, follow the exact same process as described based on your shell type, modify the fields with the following,

shell
export http_proxy=http://username:password@proxyhost:port/
export ftp_proxy=http://username:password@proxyhost:port/
export telnet_proxy=http://username:password@proxyhost:port/
export http_proxy=http://username:password@proxyhost:port/
export ftp_proxy=http://username:password@proxyhost:port/
export telnet_proxy=http://username:password@proxyhost:port/

Another approach suggested by the same user whom provided the answer on AskUbuntu for all Ubuntu users, edit the proxy configuration at the root of your machine as follows,

sh
sudo -H vim /etc/profile.d/proxy.sh
sudo -H vim /etc/profile.d/proxy.sh

And add the exported proxy members aligning the format as above, then save and reinitialize the environment, viola. The patches edited are mainly targeted for incorporating with wget, ftp, lftp, telnet in terminal.

When working with ssh instance over a proxy, a different approach has to be taken since SSH library does not natively support SOCKS5 client, user will have to pass a ProxyCommand option as a workaround to apply proxied connection, below is an instance of socat,

sh
ssh -o ProxyCommand='socat - SOCKS4A:myproxy:%h:%p,socksuser=nobody' user@host
ssh -o ProxyCommand='socat - SOCKS4A:myproxy:%h:%p,socksuser=nobody' user@host

The proxyCommand option allows user to integrate socat as an intermediary mediator to establish connection above a proxy. Other alternatives like tsocks are as well viable to transparently use SOCKS for TCP traffic, Exemplifying running SOCKS5 over socat2,

bash
ssh -o ProxyCommand='socat - "SOCKS5:%h:%p|tcp:myproxy:1080"' user@host
ssh -o ProxyCommand='socat - "SOCKS5:%h:%p|tcp:myproxy:1080"' user@host

Further, socat2 for HTTP Proxy CONNECT method,

bash
ssh -o ProxyCommand='socat - "PROXY:%h:%p|tcp:myproxy:80"' user@host
ssh -o ProxyCommand='socat - "PROXY:%h:%p|tcp:myproxy:80"' user@host
]]>
<![CDATA[Configure rclone for R2 ]]> https://note.toshiki.dev/development/rclone-for-r2 https://note.toshiki.dev/development/rclone-for-r2 Thu, 01 Jul 2021 00:00:00 GMT Configure rclone for R2

Example of how to configure rclone to use R2.

You must generate an Access Key before getting started. All examples will utilize access_key_id and access_key_secret variables which represent the Access Key ID and Secret Access Key values you generated.

With rclone installed, you may run rclone config to configure a new S3 storage provider. You will be prompted with a series of questions for the new prvider details.

If you have already configured rclone in the past, you may run rclone config file to print the location of your rclone configuration file:

bash
$ rclone config file
# Configuration file is stored at:
# ~/.config/rclone/rclone.conf
$ rclone config file
# Configuration file is stored at:
# ~/.config/rclone/rclone.conf

Then use an editor (nano or vim, for example) to add or edit the new provider. This example assumes you are adding a new r2demo provider:

bash
[r2]
type = s3
provider = Cloudflare
access_key_id = abc123 # Your access_key_id
secret_access_key = xyz456 # Your access_key_secret
endpoint = https://<accountid>.r2.cloudflarestorage.com
acl = private
[r2]
type = s3
provider = Cloudflare
access_key_id = abc123 # Your access_key_id
secret_access_key = xyz456 # Your access_key_secret
endpoint = https://<accountid>.r2.cloudflarestorage.com
acl = private

You may then use the new rclone provider for any of your normal workflows.

List buckets & objects

The rclone tree command can be used to list the contents of the remote, in this case Cloudflare R2.

bash
$ rclone tree r2demo:
# /
# ├── user-uploads
# │   └── foobar.png
# └── my-bucket-name
#     ├── cat.png
#     └── todos.txt

$ rclone tree r2demo:my-bucket-name
# /
# ├── cat.png
# └── todos.txt
$ rclone tree r2demo:
# /
# ├── user-uploads
# │   └── foobar.png
# └── my-bucket-name
#     ├── cat.png
#     └── todos.txt

$ rclone tree r2demo:my-bucket-name
# /
# ├── cat.png
# └── todos.txt

Upload and retrieve objects

The rclone copy command can be used to upload objects to an R2 bucket and vice versa - this allows you to upload files up to the 5 TB maximum object size that R2 supports.

bash
# Upload dog.txt to the user-uploads bucket
$ rclone copy dog.txt r2demo:user-uploads/dog.txt
$ rclone tree r2demo:user-uploads
# /
# ├── foobar.png
# └── dog.txt

# Download dog.txt from the user-uploads bucket
$ rclone copy r2demo:user-uploads/dog.txt dog.txt
# Upload dog.txt to the user-uploads bucket
$ rclone copy dog.txt r2demo:user-uploads/dog.txt
$ rclone tree r2demo:user-uploads
# /
# ├── foobar.png
# └── dog.txt

# Download dog.txt from the user-uploads bucket
$ rclone copy r2demo:user-uploads/dog.txt dog.txt

Generate presigned URLs

You can also generate presigned links which allow you to share public access to a file temporarily using the rclone link command.

]]>
Configure rclone for R2

Example of how to configure rclone to use R2.

You must generate an Access Key before getting started. All examples will utilize access_key_id and access_key_secret variables which represent the Access Key ID and Secret Access Key values you generated.

With rclone installed, you may run rclone config to configure a new S3 storage provider. You will be prompted with a series of questions for the new prvider details.

If you have already configured rclone in the past, you may run rclone config file to print the location of your rclone configuration file:

bash
$ rclone config file
# Configuration file is stored at:
# ~/.config/rclone/rclone.conf
$ rclone config file
# Configuration file is stored at:
# ~/.config/rclone/rclone.conf

Then use an editor (nano or vim, for example) to add or edit the new provider. This example assumes you are adding a new r2demo provider:

bash
[r2]
type = s3
provider = Cloudflare
access_key_id = abc123 # Your access_key_id
secret_access_key = xyz456 # Your access_key_secret
endpoint = https://<accountid>.r2.cloudflarestorage.com
acl = private
[r2]
type = s3
provider = Cloudflare
access_key_id = abc123 # Your access_key_id
secret_access_key = xyz456 # Your access_key_secret
endpoint = https://<accountid>.r2.cloudflarestorage.com
acl = private

You may then use the new rclone provider for any of your normal workflows.

List buckets & objects

The rclone tree command can be used to list the contents of the remote, in this case Cloudflare R2.

bash
$ rclone tree r2demo:
# /
# ├── user-uploads
# │   └── foobar.png
# └── my-bucket-name
#     ├── cat.png
#     └── todos.txt

$ rclone tree r2demo:my-bucket-name
# /
# ├── cat.png
# └── todos.txt
$ rclone tree r2demo:
# /
# ├── user-uploads
# │   └── foobar.png
# └── my-bucket-name
#     ├── cat.png
#     └── todos.txt

$ rclone tree r2demo:my-bucket-name
# /
# ├── cat.png
# └── todos.txt

Upload and retrieve objects

The rclone copy command can be used to upload objects to an R2 bucket and vice versa - this allows you to upload files up to the 5 TB maximum object size that R2 supports.

bash
# Upload dog.txt to the user-uploads bucket
$ rclone copy dog.txt r2demo:user-uploads/dog.txt
$ rclone tree r2demo:user-uploads
# /
# ├── foobar.png
# └── dog.txt

# Download dog.txt from the user-uploads bucket
$ rclone copy r2demo:user-uploads/dog.txt dog.txt
# Upload dog.txt to the user-uploads bucket
$ rclone copy dog.txt r2demo:user-uploads/dog.txt
$ rclone tree r2demo:user-uploads
# /
# ├── foobar.png
# └── dog.txt

# Download dog.txt from the user-uploads bucket
$ rclone copy r2demo:user-uploads/dog.txt dog.txt

Generate presigned URLs

You can also generate presigned links which allow you to share public access to a file temporarily using the rclone link command.

]]>
<![CDATA[Toshiki's Notebook]]> https://note.toshiki.dev/ https://note.toshiki.dev/ Thu, 01 Jul 2021 00:00:00 GMT import { VPTeamMembers } from 'vitepress/theme' const khanacademySVG = { svg: 'Khan Academy' } const members = [ { avatar: "/logos/khancademy.svg", name: "Khan Academy", title: "Khan Academy is a non-profit educational organization that provides free online learning resources.", links: [ { icon: "github", link: "https://github.com/Khan" }, { icon: khanacademySVG, link: "https://khanacademy.org" } ], }, { avatar: "/logos/khancademy.svg", name: "Khan Academy", title: "Khan Academy is a non-profit educational organization that provides free online learning resources.", links: [ { icon: "github", link: "https://github.com/Khan" }, { icon: khanacademySVG, link: "https://khanacademy.org" } ], }, { avatar: "/logos/khancademy.svg", name: "Khan Academy", title: "Khan Academy is a non-profit educational organization that provides free online learning resources.", links: [ { icon: "github", link: "https://github.com/Khan" }, { icon: khanacademySVG, link: "https://khanacademy.org" } ], }, { avatar: "/logos/khancademy.svg", name: "Khan Academy", title: "Khan Academy is a non-profit educational organization that provides free online learning resources.", links: [ { icon: "github", link: "https://github.com/Khan" }, { icon: khanacademySVG, link: "https://khanacademy.org" } ], }, { avatar: "https://avatars.githubusercontent.com/u/5837277?v=4", name: "Knut Sveidqvist", title: "Creator", links: [{ icon: "github", link: "https://github.com/knsv" }], }, ];

👀 My Learning Platforms

--> ]]>
import { VPTeamMembers } from 'vitepress/theme' const khanacademySVG = { svg: 'Khan Academy' } const members = [ { avatar: "/logos/khancademy.svg", name: "Khan Academy", title: "Khan Academy is a non-profit educational organization that provides free online learning resources.", links: [ { icon: "github", link: "https://github.com/Khan" }, { icon: khanacademySVG, link: "https://khanacademy.org" } ], }, { avatar: "/logos/khancademy.svg", name: "Khan Academy", title: "Khan Academy is a non-profit educational organization that provides free online learning resources.", links: [ { icon: "github", link: "https://github.com/Khan" }, { icon: khanacademySVG, link: "https://khanacademy.org" } ], }, { avatar: "/logos/khancademy.svg", name: "Khan Academy", title: "Khan Academy is a non-profit educational organization that provides free online learning resources.", links: [ { icon: "github", link: "https://github.com/Khan" }, { icon: khanacademySVG, link: "https://khanacademy.org" } ], }, { avatar: "/logos/khancademy.svg", name: "Khan Academy", title: "Khan Academy is a non-profit educational organization that provides free online learning resources.", links: [ { icon: "github", link: "https://github.com/Khan" }, { icon: khanacademySVG, link: "https://khanacademy.org" } ], }, { avatar: "https://avatars.githubusercontent.com/u/5837277?v=4", name: "Knut Sveidqvist", title: "Creator", links: [{ icon: "github", link: "https://github.com/knsv" }], }, ];

👀 My Learning Platforms

--> ]]>
<![CDATA[1-1: Values]]> https://note.toshiki.dev/javascript/notes/1/1-1 https://note.toshiki.dev/javascript/notes/1/1-1 Thu, 01 Jul 2021 00:00:00 GMT 1-1: Values

1-1-1: Numbers

Values of the number type are numeric values, normally written as follows,

js
144
144
  • Put this into a program, it will cause the number 144 to come into existence inside the computer, with the following bash script, 144 might looks like this in bits,

    js
    0100000001100010000000000000000000000000000000000000000000000000
    0100000001100010000000000000000000000000000000000000000000000000
  • With the following bash script, 144 will be converted into binary values in integer form,

    sh
    ip1=144 # defines a variable named ip1, with the value of 10
    echo "obase=2;$ip1" | bc # convert the value to binary via bc
    ip1=144 # defines a variable named ip1, with the value of 10
    echo "obase=2;$ip1" | bc # convert the value to binary via bc
    • The variable ip1 is assigned the value 144.
    • The echo command prints out the string "obase=2;144", where "obase=2;" is an argument for bc that tells it to output the result in base 2 (binary), and "10" is the decimal number we want to convert.
    • The output of the echo command is piped (using the | character) to bc, which takes the input "obase=2;144" and interprets it as a command to convert the number 10 to binary.
    • Finally, the binary equivalent of 144, which is "10010000", is printed to the terminal.

TIP

But the standard describes JavaScript numbers as 64-bit floating-point values, which indicates fractions and exponents are available.

Not all whole numbers 101910^{19} fit in a JavaScript number. There are also negative numbers, so one of the bits has to be used to store the sign of the number.

  • 11 bits are used to store the position of the decimal dot within the number.
  • 52 bits, any whole number less than 2522^{52}, which is more than 101510^{15} will safely fit in a JavaScript number, numbers we are using stay well below that.

Fractional numbers are written by using a dot,

js
9.81
9.81

For extreme huge or tiny numbers, we can also use "scientific" notion by adding an e, followed by the exponent of the number,

js
2.998e8
2.998e8

This indicates 2.998×108=299800002.998 \times 10^8 = 29980000.

Calculations with whole numbers (referred as integers) that fits into 52 bits are guaranteed to be always precise, but calculation with fraction numbers are generally not.

  • Such as π\pi cannot be precisely expressed by a finite amount of decimal digits, thus many numbers lose some precision when only 64 bits are available to store them.
1-1-1: Numbers review
  • 64 bits: A 64-bit number is a binary sequence of 64 bits, which can represent 2642^{64} (18,446,744,073,709,551,616) different values. This is commonly used for representing memory addresses and integers with large values in computer systems.
  • 11 bits: An 11-bit number is a binary sequence of 11 bits, which can represent 2112^{11} (2,048) different values. This is often used in computer systems for encoding small integers, such as color values in images.
  • 52 bits: A 52-bit number is a binary sequence of 52 bits, which can represent 2522^{52} (4,503,599,627,370,496) different values. This is often used for representing the significand or mantissa portion of a floating-point number in computer systems.

1-1-2: Arithmetic

The main thing to do with numbers is arithmetic. Arithmetic operations such as addition or multiplication take two number values and produce a new number from them, the following is an example of calculation in JavaScript.

js
100 + 4 * 11
100 + 4 * 11
  • The + and * symbols are called operators.

    • + apparently stands for addition while * stands for multiplication.
  • This expression indicates the multiplication takes place first then the adding of 100 comes next as a regard to PEMDAS rules (Order of Operations).

But we can still overwrite the steps of operation using a parenthesis around the addition,

js
;(100 + 4) * 11
;(100 + 4) * 11

For subtraction, there is the - operator, and division can be done with /. When operators appear together without parentheses, they are applied is determined by the precedence of the operators.

  • When multiple operators with the same precedence appear next to each other (as 1-2+1), they are applied left to right (refers to PEMDAS).
  • Precedence: Priorities.

WARNING

When is doubt, don't care about precedence, just add parentheses for order of operation.

There is one more arithmetic operator, which is the % percent sign used to represent the modulo operation. The term "X modulo Y" is defined as the remainder of dividing X by Y.

  • For example, 314 % 100 is 14, 10 % 3 is 1, and 144 % 12 is 0 because there are no remainders.
  • Modulo's precedence is the same as that of multiplication and division.
1-2: Arithmetic review
  • All of the operators in JavaScript follows precedence rules, or referred as PEMDAS in conventional math.
    • + and - has the same lowest precedence.
    • * , / and % has the same medium precedence.
    • () has the highest precedence, followed on with brackets.
  • The symbol % refers to "modulo", in mathematical reading, we say "X modulo Y" is the remainder of X over Y.

1-1-3: Strings

The next data type is the string. Its use is not as evident from its name as with numbers, it also fulfills a very basic role.

  • Strings are used to represent text.
  • Strings are usually written by enclosing the contents with quotes.
js
'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'

TIP

Both single and double quotes can be used to mark strings

  • As long as the quotes at the start and the end of the string match.

Almost anything can be put between quotes, and JavaScript will make a string value out of it. But the followings are tricky to be put between quotes.

  • Newlines: The things we get when we press enter on keyboard. We uses \n to represent.
  • New tab: Similarly like newlines, \t indicates a new tab being indented.

Take the following string as an example,

js
'Lorem ipsum dolor sit amet,\n consectetur adipiscing elit.'
'Lorem ipsum dolor sit amet,\n consectetur adipiscing elit.'

The following will be the rendered output,

js
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.

WARNING

But the situations where we want a backslash in a string to just be a backslash instead of a special code. By using \\ would render the "just slash" to \ on output, instead of a special character, as follows,

js
"A newline character is written like \"\\n\"."
"A newline character is written like \"\\n\"."

Strings cannot be divided, multiplied, or subtracted, unlike integers. But the + operator can be used on the. It concatenates (glues) the two strings together, the following example will produce the string "concatenate".

js
'con' + 'cat' + 'e' + 'nate'
'con' + 'cat' + 'e' + 'nate'
1-1-3: Strings review
  • Nearly everything could be put into strings in JavaScript
  • String could be wrapped with "" double quotation marks or '' single quotation marks.
  • There is a tricky situation in JavaScript's string, where \ backslash followed with a character are being introduced specially by the interpreter, such as \n referred as newline, \t referred as new tab.
    • \\ double backslash will be rendered as a single \.
    • \& symbols followed after slash will not contain its original function such as connecting, but will be rendered as & on output.

1-1-3-FR: Further Reading

From the example given in the prior section with a lot of backslashes, it might be hard to understand the concept on at what time the slash will be rendered and when it will be considered as a special character starter.

The example is given as,

js
"A newline character is written like \"\\n\"."
"A newline character is written like \"\\n\"."

The rendered output will be on print,

js
A newline character is written like "\n".
A newline character is written like "\n".

the backslash character (\) is used as an escape character to indicate that the following character(s) should be treated specially. In this case, the "\n" sequence is an escape sequence that represents a newline character. The backslash before the n character tells the JavaScript interpreter that it should treat the n as a special character and not just as the letter "n".

However, if we want to include an actual backslash character (\), we will have to escape it by using to two backslashes \\, or else with one single slash the JavaScript interpreter will still determines it as an special operator, Thus \\ will print \ on output.

  • But what about the quotation marks used within the quotation marks that wraps the string? Wouldn't JavaScript interpreter throw error?

    • In the given JavaScript string, the inner set of double quotation marks ("\\n") is escaped using a backslash (\) character. This tells the JavaScript interpreter to treat the inner double quotation marks as a regular character instead of a string delimiter.

      So when the string is rendered on output, the backslash character will be removed and the inner set of quotation marks will be displayed as a regular character. The rendered string will look like this,

      js
      '\n'
      '\n'

      The outer set of double quotation marks in the original string delimit the entire string and will be displayed as regular quotation marks.

Source: ChatGPT CA (Code Analysis)

]]>
1-1: Values

1-1-1: Numbers

Values of the number type are numeric values, normally written as follows,

js
144
144
  • Put this into a program, it will cause the number 144 to come into existence inside the computer, with the following bash script, 144 might looks like this in bits,

    js
    0100000001100010000000000000000000000000000000000000000000000000
    0100000001100010000000000000000000000000000000000000000000000000
  • With the following bash script, 144 will be converted into binary values in integer form,

    sh
    ip1=144 # defines a variable named ip1, with the value of 10
    echo "obase=2;$ip1" | bc # convert the value to binary via bc
    ip1=144 # defines a variable named ip1, with the value of 10
    echo "obase=2;$ip1" | bc # convert the value to binary via bc
    • The variable ip1 is assigned the value 144.
    • The echo command prints out the string "obase=2;144", where "obase=2;" is an argument for bc that tells it to output the result in base 2 (binary), and "10" is the decimal number we want to convert.
    • The output of the echo command is piped (using the | character) to bc, which takes the input "obase=2;144" and interprets it as a command to convert the number 10 to binary.
    • Finally, the binary equivalent of 144, which is "10010000", is printed to the terminal.

TIP

But the standard describes JavaScript numbers as 64-bit floating-point values, which indicates fractions and exponents are available.

Not all whole numbers 101910^{19} fit in a JavaScript number. There are also negative numbers, so one of the bits has to be used to store the sign of the number.

  • 11 bits are used to store the position of the decimal dot within the number.
  • 52 bits, any whole number less than 2522^{52}, which is more than 101510^{15} will safely fit in a JavaScript number, numbers we are using stay well below that.

Fractional numbers are written by using a dot,

js
9.81
9.81

For extreme huge or tiny numbers, we can also use "scientific" notion by adding an e, followed by the exponent of the number,

js
2.998e8
2.998e8

This indicates 2.998×108=299800002.998 \times 10^8 = 29980000.

Calculations with whole numbers (referred as integers) that fits into 52 bits are guaranteed to be always precise, but calculation with fraction numbers are generally not.

  • Such as π\pi cannot be precisely expressed by a finite amount of decimal digits, thus many numbers lose some precision when only 64 bits are available to store them.
1-1-1: Numbers review
  • 64 bits: A 64-bit number is a binary sequence of 64 bits, which can represent 2642^{64} (18,446,744,073,709,551,616) different values. This is commonly used for representing memory addresses and integers with large values in computer systems.
  • 11 bits: An 11-bit number is a binary sequence of 11 bits, which can represent 2112^{11} (2,048) different values. This is often used in computer systems for encoding small integers, such as color values in images.
  • 52 bits: A 52-bit number is a binary sequence of 52 bits, which can represent 2522^{52} (4,503,599,627,370,496) different values. This is often used for representing the significand or mantissa portion of a floating-point number in computer systems.

1-1-2: Arithmetic

The main thing to do with numbers is arithmetic. Arithmetic operations such as addition or multiplication take two number values and produce a new number from them, the following is an example of calculation in JavaScript.

js
100 + 4 * 11
100 + 4 * 11
  • The + and * symbols are called operators.

    • + apparently stands for addition while * stands for multiplication.
  • This expression indicates the multiplication takes place first then the adding of 100 comes next as a regard to PEMDAS rules (Order of Operations).

But we can still overwrite the steps of operation using a parenthesis around the addition,

js
;(100 + 4) * 11
;(100 + 4) * 11

For subtraction, there is the - operator, and division can be done with /. When operators appear together without parentheses, they are applied is determined by the precedence of the operators.

  • When multiple operators with the same precedence appear next to each other (as 1-2+1), they are applied left to right (refers to PEMDAS).
  • Precedence: Priorities.

WARNING

When is doubt, don't care about precedence, just add parentheses for order of operation.

There is one more arithmetic operator, which is the % percent sign used to represent the modulo operation. The term "X modulo Y" is defined as the remainder of dividing X by Y.

  • For example, 314 % 100 is 14, 10 % 3 is 1, and 144 % 12 is 0 because there are no remainders.
  • Modulo's precedence is the same as that of multiplication and division.
1-2: Arithmetic review
  • All of the operators in JavaScript follows precedence rules, or referred as PEMDAS in conventional math.
    • + and - has the same lowest precedence.
    • * , / and % has the same medium precedence.
    • () has the highest precedence, followed on with brackets.
  • The symbol % refers to "modulo", in mathematical reading, we say "X modulo Y" is the remainder of X over Y.

1-1-3: Strings

The next data type is the string. Its use is not as evident from its name as with numbers, it also fulfills a very basic role.

  • Strings are used to represent text.
  • Strings are usually written by enclosing the contents with quotes.
js
'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'

TIP

Both single and double quotes can be used to mark strings

  • As long as the quotes at the start and the end of the string match.

Almost anything can be put between quotes, and JavaScript will make a string value out of it. But the followings are tricky to be put between quotes.

  • Newlines: The things we get when we press enter on keyboard. We uses \n to represent.
  • New tab: Similarly like newlines, \t indicates a new tab being indented.

Take the following string as an example,

js
'Lorem ipsum dolor sit amet,\n consectetur adipiscing elit.'
'Lorem ipsum dolor sit amet,\n consectetur adipiscing elit.'

The following will be the rendered output,

js
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.

WARNING

But the situations where we want a backslash in a string to just be a backslash instead of a special code. By using \\ would render the "just slash" to \ on output, instead of a special character, as follows,

js
"A newline character is written like \"\\n\"."
"A newline character is written like \"\\n\"."

Strings cannot be divided, multiplied, or subtracted, unlike integers. But the + operator can be used on the. It concatenates (glues) the two strings together, the following example will produce the string "concatenate".

js
'con' + 'cat' + 'e' + 'nate'
'con' + 'cat' + 'e' + 'nate'
1-1-3: Strings review
  • Nearly everything could be put into strings in JavaScript
  • String could be wrapped with "" double quotation marks or '' single quotation marks.
  • There is a tricky situation in JavaScript's string, where \ backslash followed with a character are being introduced specially by the interpreter, such as \n referred as newline, \t referred as new tab.
    • \\ double backslash will be rendered as a single \.
    • \& symbols followed after slash will not contain its original function such as connecting, but will be rendered as & on output.

1-1-3-FR: Further Reading

From the example given in the prior section with a lot of backslashes, it might be hard to understand the concept on at what time the slash will be rendered and when it will be considered as a special character starter.

The example is given as,

js
"A newline character is written like \"\\n\"."
"A newline character is written like \"\\n\"."

The rendered output will be on print,

js
A newline character is written like "\n".
A newline character is written like "\n".

the backslash character (\) is used as an escape character to indicate that the following character(s) should be treated specially. In this case, the "\n" sequence is an escape sequence that represents a newline character. The backslash before the n character tells the JavaScript interpreter that it should treat the n as a special character and not just as the letter "n".

However, if we want to include an actual backslash character (\), we will have to escape it by using to two backslashes \\, or else with one single slash the JavaScript interpreter will still determines it as an special operator, Thus \\ will print \ on output.

  • But what about the quotation marks used within the quotation marks that wraps the string? Wouldn't JavaScript interpreter throw error?

    • In the given JavaScript string, the inner set of double quotation marks ("\\n") is escaped using a backslash (\) character. This tells the JavaScript interpreter to treat the inner double quotation marks as a regular character instead of a string delimiter.

      So when the string is rendered on output, the backslash character will be removed and the inner set of quotation marks will be displayed as a regular character. The rendered string will look like this,

      js
      '\n'
      '\n'

      The outer set of double quotation marks in the original string delimit the entire string and will be displayed as regular quotation marks.

Source: ChatGPT CA (Code Analysis)

]]>
<![CDATA[1-2]]> https://note.toshiki.dev/javascript/notes/1/1-2 https://note.toshiki.dev/javascript/notes/1/1-2 Thu, 01 Jul 2021 00:00:00 GMT <![CDATA[俊樹のノート]]> https://note.toshiki.dev/jp/ https://note.toshiki.dev/jp/ Thu, 01 Jul 2021 00:00:00 GMT import { VPTeamMembers } from 'vitepress/theme' const khanacademySVG = { svg: 'Khan Academy' } const members = [ { avatar: "/logos/khancademy.svg", name: "Khan Academy", title: "Khan Academy is a non-profit educational organization that provides free online learning resources.", links: [ { icon: "github", link: "https://github.com/Khan" }, { icon: khanacademySVG, link: "https://khanacademy.org" } ], }, { avatar: "/logos/khancademy.svg", name: "Khan Academy", title: "Khan Academy is a non-profit educational organization that provides free online learning resources.", links: [ { icon: "github", link: "https://github.com/Khan" }, { icon: khanacademySVG, link: "https://khanacademy.org" } ], }, { avatar: "/logos/khancademy.svg", name: "Khan Academy", title: "Khan Academy is a non-profit educational organization that provides free online learning resources.", links: [ { icon: "github", link: "https://github.com/Khan" }, { icon: khanacademySVG, link: "https://khanacademy.org" } ], }, { avatar: "/logos/khancademy.svg", name: "Khan Academy", title: "Khan Academy is a non-profit educational organization that provides free online learning resources.", links: [ { icon: "github", link: "https://github.com/Khan" }, { icon: khanacademySVG, link: "https://khanacademy.org" } ], }, { avatar: "https://avatars.githubusercontent.com/u/5837277?v=4", name: "Knut Sveidqvist", title: "Creator", links: [{ icon: "github", link: "https://github.com/knsv" }], }, ];

👀 My Learning Platforms

--> ]]>
import { VPTeamMembers } from 'vitepress/theme' const khanacademySVG = { svg: 'Khan Academy' } const members = [ { avatar: "/logos/khancademy.svg", name: "Khan Academy", title: "Khan Academy is a non-profit educational organization that provides free online learning resources.", links: [ { icon: "github", link: "https://github.com/Khan" }, { icon: khanacademySVG, link: "https://khanacademy.org" } ], }, { avatar: "/logos/khancademy.svg", name: "Khan Academy", title: "Khan Academy is a non-profit educational organization that provides free online learning resources.", links: [ { icon: "github", link: "https://github.com/Khan" }, { icon: khanacademySVG, link: "https://khanacademy.org" } ], }, { avatar: "/logos/khancademy.svg", name: "Khan Academy", title: "Khan Academy is a non-profit educational organization that provides free online learning resources.", links: [ { icon: "github", link: "https://github.com/Khan" }, { icon: khanacademySVG, link: "https://khanacademy.org" } ], }, { avatar: "/logos/khancademy.svg", name: "Khan Academy", title: "Khan Academy is a non-profit educational organization that provides free online learning resources.", links: [ { icon: "github", link: "https://github.com/Khan" }, { icon: khanacademySVG, link: "https://khanacademy.org" } ], }, { avatar: "https://avatars.githubusercontent.com/u/5837277?v=4", name: "Knut Sveidqvist", title: "Creator", links: [{ icon: "github", link: "https://github.com/knsv" }], }, ];

👀 My Learning Platforms

--> ]]>
<![CDATA[Theme ]]> https://note.toshiki.dev/roadmap https://note.toshiki.dev/roadmap Thu, 01 Jul 2021 00:00:00 GMT Theme

Homepage

  • Finish three hero action blocks with keywords and its corresponded descriptions.

  • Finish my learning platform section using SVGs of different online academies from simple icons.

    • Descriptions

    • Icon in SVG format

    • Platform name

    • Linkable SVG icon/button

      • Khan academy
      • GitHub
      • Libretext
      • OpenStax
      • BCcampus
      • Wikibooks
      • Wikipedia
      • Bookboon
      • [ ]

Configs

  • Header configs including different properties and meta configs.
  • Complete navigation configuration.
    • Navigation divider and text title, line breakings.
  • Complete sidebar configs for different directories.
  • Vitepress sidebar generation plugin for huge bundled clips article directory.

Articles

  • <head> tag documentation or guide by joshbuchea/HEAD.
  • Write index page for every directory, no Chat GPT allowed.
  • Chemistry review notes.
  • JavaScript 0-100 notes per chapter.
    • Marijn Haverbeke - Eloquent JavaScript_ A Modern Introduction to Programming (2011, No Starch Press)
  • Outliers novel clips
  • Migrate clipped articles and archives from Notion to Vitepress.
  • Fresh copy of "How To Ask Questions The Smart Way" by Eric Steven Raymond
]]>
Theme

Homepage

  • Finish three hero action blocks with keywords and its corresponded descriptions.

  • Finish my learning platform section using SVGs of different online academies from simple icons.

    • Descriptions

    • Icon in SVG format

    • Platform name

    • Linkable SVG icon/button

      • Khan academy
      • GitHub
      • Libretext
      • OpenStax
      • BCcampus
      • Wikibooks
      • Wikipedia
      • Bookboon
      • [ ]

Configs

  • Header configs including different properties and meta configs.
  • Complete navigation configuration.
    • Navigation divider and text title, line breakings.
  • Complete sidebar configs for different directories.
  • Vitepress sidebar generation plugin for huge bundled clips article directory.

Articles

  • <head> tag documentation or guide by joshbuchea/HEAD.
  • Write index page for every directory, no Chat GPT allowed.
  • Chemistry review notes.
  • JavaScript 0-100 notes per chapter.
    • Marijn Haverbeke - Eloquent JavaScript_ A Modern Introduction to Programming (2011, No Starch Press)
  • Outliers novel clips
  • Migrate clipped articles and archives from Notion to Vitepress.
  • Fresh copy of "How To Ask Questions The Smart Way" by Eric Steven Raymond
]]>
<![CDATA[Welcome to Reading Notes ]]> https://note.toshiki.dev/save/reading/ https://note.toshiki.dev/save/reading/ Thu, 01 Jul 2021 00:00:00 GMT Welcome to Reading Notes ]]> Welcome to Reading Notes ]]> <![CDATA[Introduction & Chapter 1: The Roseto Mystery]]> https://note.toshiki.dev/save/reading/outliers/1 https://note.toshiki.dev/save/reading/outliers/1 Thu, 01 Jul 2021 00:00:00 GMT Introduction & Chapter 1: The Roseto Mystery

Summary: Introduction: The Roseto Mystery

Section 1.

In the late 1800s, immigrants from Roseto Valfortore, Italy, came to Pennsylvania to work in the slate quarry near the town of Bangor. The settlers established a new community, named after their old one: Roseto. They built schools, a park, small shops, and more than a dozen factories. They kept to themselves and did not interact much with the predominantly German and English populations of the towns around them.

In the 1950s, a local doctor told Stewart Wolf, a medical researcher, that hardly anyone in Roseto under age sixty-five had heart disease. Wolf was curious. He did blood draws and EKG scans, and he analyzed physicians’ records and death certificates. Wolf was amazed that almost no one under fifty-five showed any signs of heart disease, which at the time was America’s leading cause of death in men under sixty-five. Wolf enlisted the help of John Bruhn, a sociologist. They found that there was no suicide, alcoholism, or drug addiction in Roseto: everyone seemed to be dying of old age. According to Gladwell, Roseto was an outlier.

Section 2.

Wolf was forced to rule out diet and lifestyle as explanations, because the Rosetans had poor eating habits, smoked heavily, and were obese. He ruled out genetics after determining that Rosetans’ relatives in other parts of the country were not in comparably good health. Wolf eventually decided that what made Roseto’s inhabitants so healthy was the town itself—its culture and social structure. Many homes contained three generations living together, and with a population of just two thousand people, there were twenty-two separate civic organizations.

Wolf and Bruhn were met with a great deal of skepticism. They had to work hard to convince the medical establishment that the values of where we live and the people around us have a significant impact on who we are. Gladwell wants Outliers to do for our understanding of success what Wolf did for our understanding of health.

Summary: Chapter One: The Matthew Effect

Section 1.

Gladwell describes a game between two teams in the Canadian Hockey League, the most competitive junior hockey league in the world. Starting at a very young age, players are regularly assessed for talent, so that the best can be separated out and prepared for the next level. The system is designed to be a meritocracy.

Section 2.

Gladwell wants to show that circumstances matter just as much for success as work ethic or intelligence. People often ask about the lifestyle, intelligence, or special talents of successful individuals, but not enough people ask when and where a person grew up. Gladwell likens people to trees: we all know that the tallest trees received the most sunlight, had nutrient-rich soil, and were lucky enough to avoid lumberjacks. He suggests that we study the environmental and social influences that make people successful.

Section 3.

In the 1980s, Canadian psychologist Roger Barnsley observed that on elite Canadian hockey teams, whether youth league or NHL, a disproportionate number of players have birthdays in the first three months of the year.

Section 4.

The explanation for the distribution of birthdays is simple: the cutoff date for an individual’s league assignment is January 1. A player born on January 2 will be 12 months older than one born at the end of December. At the age of nine or ten, this often translates into a huge difference in size, coordination, and maturity. By age ten, coaches regularly pick the oldest and largest potential players for the more competitive “rep squads,” where the players will receive better coaching, have more practice time, and play many more games. By thirteen or fourteen, all of the extra experience and coaching will have actually made the players better, and they will be selected for the more competitive league(s). The same thing happens in American youth baseball and European soccer, but with different cutoff dates.

The phenomenon is also observable in education. Economists Kelly Bedard and Elizabeth Dhuey found that on math and science tests, the older children in fourth grade regularly score better than the youngest children. This can affect whether a child qualifies for a gifted program. When Bedard and Dhuey extended their analysis to four-year colleges, they found that the students who belonged to the relatively youngest group were underrepresented by more than 10 percent.

Section 5.

The top-level hockey players were given opportunities they neither deserved nor earned. Sociologist Robert Merton called this the “Matthew Effect,” after the verse in the Gospel of Matthew:

“For unto everyone that hath shall be given, and he shall have abundance. But from that hath not shall be taken away even that which he hath.”

The successful receive more resources: the best students receive the best teaching, the richest citizens get the biggest tax breaks, the largest kids get the best coaching. Sociologists call this “accumulative advantage.” Gladwell points out that cutoff dates exclude nearly half of the potential athletes from a population. Junior hockey teams in the Czech Republic show the same unbalanced distribution of birthdays as in Canada. If Canada or the Czech Republic separated each of their youth leagues into two separate leagues, one for kids born in the first half of the year, and one for kids born in the second half of the year, they would have twice as many athletes available for their national teams. Similarly, schools could separate kindergarten classes into students born in the first, middle, and last four months of the year. The benefits would justify the added administrative work, but, writes Gladwell, the scheme would run afoul of society’s need to believe that individual merit matters more than the rules society has created.

Section 6.

Gord Wasden, the father of one of the Canadian Hockey League boys from the first section, describes his son. Scott Wasden worked hard to get where he is, but he has also generally had the advantage of being big compared to others on his team. He was born on January 4.

Analysis: Introduction: The Roseto Mystery & Chapter 1: The Matthew Effect

Gladwell's thesis argues that that the idea of rugged, individual success is not accurate. Rather, the most successful person doesn’t thrive without some environmental and social influence plus a dose of good fortune.  After laying out the concepts of a meritocracy and suggesting that this is the way that hockey players advance in Canada, he immediately undercuts this idea. Gladwell uses the illustration of birthday distribution as an example of an invisible contributor to the success of hockey players. With a registration cutoff date of January 1, players born from January 2 through March 31 are older than teammates born later in the year. These older players are likely bigger, faster, more coordinated, and more mature. Since the older players are seen as more skilled, they get selected for more advanced leagues with more practice, more games, and higher-quality coaching. By the time these older players reach their early teens, the extra advantages gained from being judged better because of their birthday translate into being better players. Similarly, the age cutoff for school registrations often mistakes maturity for ability. As a result, the older children appear smarter, get put into advanced groups, and qualify for gifted programs. The birthdate bias carries through to college.

Advantages result in more advantages. Gladwell reinforces this idea with the “Matthew Effect,” which states that "success leads to more success." More simply: by being a little bit better, a hockey player will get opportunities that may result in the player becoming an outlier. Gladwell implies that the systems that determine success are not efficient. He asks readers to question the way we, as a society, think about success. He suggests that changing the systems in athletics and education would chip away at the myth of individual merit as the chief marker of success and help level the playing field. Gladwell's model for this phenomenon is hockey player Scott Wasden. By demonstrating that Scott had the passion, talent, and work ethic for the game, as well as the good luck to be born on January 4, Gladwell reasons that Wasden, like many others he will be profiling, benefit by being both good and lucky.

Reference

  • “Outliers Introduction & Chapter 1 Summary & Analysis.” SparkNotes, www.sparknotes.com/lit/outliers/section1/.
]]>
Introduction & Chapter 1: The Roseto Mystery

Summary: Introduction: The Roseto Mystery

Section 1.

In the late 1800s, immigrants from Roseto Valfortore, Italy, came to Pennsylvania to work in the slate quarry near the town of Bangor. The settlers established a new community, named after their old one: Roseto. They built schools, a park, small shops, and more than a dozen factories. They kept to themselves and did not interact much with the predominantly German and English populations of the towns around them.

In the 1950s, a local doctor told Stewart Wolf, a medical researcher, that hardly anyone in Roseto under age sixty-five had heart disease. Wolf was curious. He did blood draws and EKG scans, and he analyzed physicians’ records and death certificates. Wolf was amazed that almost no one under fifty-five showed any signs of heart disease, which at the time was America’s leading cause of death in men under sixty-five. Wolf enlisted the help of John Bruhn, a sociologist. They found that there was no suicide, alcoholism, or drug addiction in Roseto: everyone seemed to be dying of old age. According to Gladwell, Roseto was an outlier.

Section 2.

Wolf was forced to rule out diet and lifestyle as explanations, because the Rosetans had poor eating habits, smoked heavily, and were obese. He ruled out genetics after determining that Rosetans’ relatives in other parts of the country were not in comparably good health. Wolf eventually decided that what made Roseto’s inhabitants so healthy was the town itself—its culture and social structure. Many homes contained three generations living together, and with a population of just two thousand people, there were twenty-two separate civic organizations.

Wolf and Bruhn were met with a great deal of skepticism. They had to work hard to convince the medical establishment that the values of where we live and the people around us have a significant impact on who we are. Gladwell wants Outliers to do for our understanding of success what Wolf did for our understanding of health.

Summary: Chapter One: The Matthew Effect

Section 1.

Gladwell describes a game between two teams in the Canadian Hockey League, the most competitive junior hockey league in the world. Starting at a very young age, players are regularly assessed for talent, so that the best can be separated out and prepared for the next level. The system is designed to be a meritocracy.

Section 2.

Gladwell wants to show that circumstances matter just as much for success as work ethic or intelligence. People often ask about the lifestyle, intelligence, or special talents of successful individuals, but not enough people ask when and where a person grew up. Gladwell likens people to trees: we all know that the tallest trees received the most sunlight, had nutrient-rich soil, and were lucky enough to avoid lumberjacks. He suggests that we study the environmental and social influences that make people successful.

Section 3.

In the 1980s, Canadian psychologist Roger Barnsley observed that on elite Canadian hockey teams, whether youth league or NHL, a disproportionate number of players have birthdays in the first three months of the year.

Section 4.

The explanation for the distribution of birthdays is simple: the cutoff date for an individual’s league assignment is January 1. A player born on January 2 will be 12 months older than one born at the end of December. At the age of nine or ten, this often translates into a huge difference in size, coordination, and maturity. By age ten, coaches regularly pick the oldest and largest potential players for the more competitive “rep squads,” where the players will receive better coaching, have more practice time, and play many more games. By thirteen or fourteen, all of the extra experience and coaching will have actually made the players better, and they will be selected for the more competitive league(s). The same thing happens in American youth baseball and European soccer, but with different cutoff dates.

The phenomenon is also observable in education. Economists Kelly Bedard and Elizabeth Dhuey found that on math and science tests, the older children in fourth grade regularly score better than the youngest children. This can affect whether a child qualifies for a gifted program. When Bedard and Dhuey extended their analysis to four-year colleges, they found that the students who belonged to the relatively youngest group were underrepresented by more than 10 percent.

Section 5.

The top-level hockey players were given opportunities they neither deserved nor earned. Sociologist Robert Merton called this the “Matthew Effect,” after the verse in the Gospel of Matthew:

“For unto everyone that hath shall be given, and he shall have abundance. But from that hath not shall be taken away even that which he hath.”

The successful receive more resources: the best students receive the best teaching, the richest citizens get the biggest tax breaks, the largest kids get the best coaching. Sociologists call this “accumulative advantage.” Gladwell points out that cutoff dates exclude nearly half of the potential athletes from a population. Junior hockey teams in the Czech Republic show the same unbalanced distribution of birthdays as in Canada. If Canada or the Czech Republic separated each of their youth leagues into two separate leagues, one for kids born in the first half of the year, and one for kids born in the second half of the year, they would have twice as many athletes available for their national teams. Similarly, schools could separate kindergarten classes into students born in the first, middle, and last four months of the year. The benefits would justify the added administrative work, but, writes Gladwell, the scheme would run afoul of society’s need to believe that individual merit matters more than the rules society has created.

Section 6.

Gord Wasden, the father of one of the Canadian Hockey League boys from the first section, describes his son. Scott Wasden worked hard to get where he is, but he has also generally had the advantage of being big compared to others on his team. He was born on January 4.

Analysis: Introduction: The Roseto Mystery & Chapter 1: The Matthew Effect

Gladwell's thesis argues that that the idea of rugged, individual success is not accurate. Rather, the most successful person doesn’t thrive without some environmental and social influence plus a dose of good fortune.  After laying out the concepts of a meritocracy and suggesting that this is the way that hockey players advance in Canada, he immediately undercuts this idea. Gladwell uses the illustration of birthday distribution as an example of an invisible contributor to the success of hockey players. With a registration cutoff date of January 1, players born from January 2 through March 31 are older than teammates born later in the year. These older players are likely bigger, faster, more coordinated, and more mature. Since the older players are seen as more skilled, they get selected for more advanced leagues with more practice, more games, and higher-quality coaching. By the time these older players reach their early teens, the extra advantages gained from being judged better because of their birthday translate into being better players. Similarly, the age cutoff for school registrations often mistakes maturity for ability. As a result, the older children appear smarter, get put into advanced groups, and qualify for gifted programs. The birthdate bias carries through to college.

Advantages result in more advantages. Gladwell reinforces this idea with the “Matthew Effect,” which states that "success leads to more success." More simply: by being a little bit better, a hockey player will get opportunities that may result in the player becoming an outlier. Gladwell implies that the systems that determine success are not efficient. He asks readers to question the way we, as a society, think about success. He suggests that changing the systems in athletics and education would chip away at the myth of individual merit as the chief marker of success and help level the playing field. Gladwell's model for this phenomenon is hockey player Scott Wasden. By demonstrating that Scott had the passion, talent, and work ethic for the game, as well as the good luck to be born on January 4, Gladwell reasons that Wasden, like many others he will be profiling, benefit by being both good and lucky.

Reference

  • “Outliers Introduction & Chapter 1 Summary & Analysis.” SparkNotes, www.sparknotes.com/lit/outliers/section1/.
]]>
<![CDATA[Chapter Two: The 10,000-Hour Rule]]> https://note.toshiki.dev/save/reading/outliers/2 https://note.toshiki.dev/save/reading/outliers/2 Thu, 01 Jul 2021 00:00:00 GMT Chapter Two: The 10,000-Hour Rule

Summary: Chapter Two: The 10,000-Hour Rule

Section 1.

Bill Joy, a co-founder of Sun Microsystems, is one of the most influential computer programmers of all time. Joy attended the University of Michigan, thinking to become a biologist or mathematician, but he became obsessed with the Computer Center that opened during his freshman year. In 1975, he enrolled in graduate school at UC Berkeley. At both schools, Bill Joy spent much of his free time programming. After graduating from Berkeley, he founded Sun Microsystems, eventually rewriting the Java programming language. He would appear to be a good example of success based on individual merit.

Section 2.

If achievement is the combination of talent and preparation, how much does innate talent affect one’s success? In the 1990s, a study at Berlin’s elite Academy of Music determined that, regardless of instrument, all of the world-class students had practiced more than 10,000 hours. They did not find anyone at the top level who spent less time, nor did they find anyone who spent that amount of time who was not successful. Neurologist Daniel Levitin states that, across many fields, world-class expertise is never accomplished in less than 10,000 hours. The law holds even for a prodigy like Mozart, who started composing at age six: he did not compose his first masterwork until he was twenty-one. The youth athletes from the previous chapter who made it to the professional level put in 10,000 hours of practice. And note: individuals cannot normally put in that much practice without help. Most people will need supportive parents, financial stability, and probably a special program—like an all-star youth hockey team.

Section 3.

Bill Joy was certainly intelligent, having achieved a perfect score on the math portion of his Scholastic Aptitude Test. His opportunities, however, were extraordinary. Bill Joy happened to choose a college that had a time-sharing computer available, something that was exceedingly rare during the early 1970s. While most students had to pay for computer time, Bill Joy exploited a bug in the college’s system to gain unlimited access to the Computer Center, which was walking distance from where he lived. He was able to spend almost all of his free time programming, and when he went to Berkeley, he had a terminal at home, where he could program until he fell asleep at his keyboard. Bill Joy was able to accumulate 10,000 hours while in college.

Section 4.

The Beatles are another example of the 10,000-hours principle. In 1960, when they were still a high school rock band, they were given the chance to travel to Hamburg, Germany and play in various strip clubs. The Beatles were contracted to play for hours every night, seven nights a week, and thereby were forced to develop as musicians. After a year and a half, they had performed 270 nights. By 1964, when they first found commercial success, they had performed an estimated twelve hundred times—more than most band bands do in an entire career.

Section 5.

Born in Seattle to affluent parents, Bill Gates was sent to a private school for seventh grade. The school’s Mother’s Club funded the purchase of a time-sharing terminal connected to a mainframe computer in Seattle. As an eighth-grader, Gates was able to start programming. When the Mother’s Club could no longer pay for computing time, Gates was able to continue programming at Information Sciences, Inc. (ISI) through a connection he made with one of the school parents. After that, one of ISI’s founders recommended Gates for a programming project at the Bonneville Power station. Gates was able to leave high school during his senior year to program for the Bonneville Power station as an independent study project. By the time Bill Gates dropped out of Harvard, he was well past 10,000 hours of experience.

Section 6.

In a list of the seventy-five richest people in human history, going as far back as ancient Egypt and converting all wealth estimates into modern U.S. dollars, fourteen names are Americans born within nine years of one another (including John D. Rockefeller and J.P. Morgan). What accounts for the fact that a list that covers thousands of years should have 20 percent of its members so close together? The fourteen Americans happened to live during the 1860s and 1870s, when the American economy was undergoing a huge transformation: the expansion of the railroads and the creation of Wall Street. Gladwell argues that the fourteen names are so close in birth date because they were all the perfect age to seize the opportunities available.

Bill Joy and Bill Gates were also born at just the right time. In 1975, Popular Electronics ran a cover story about the Altair 8800, a $397 microcomputer kit. Someone born before 1954 would likely already have a job with IBM, working on mainframes. Someone born after 1956 would likely still be in high school. Most of the biggest pioneers in the modern computer industry, including Bill Gates, Bill Joy, Steve Jobs, and Eric Schmidt, were born in 1954 or 1955, as were Joy’s three fellow founders at Sun.

Analysis: Chapter Two: The 10,000-Hour Rule

Gladwell introduces his controversial and widely disputed 10,000 hours rule. Simply put, the rule suggests that to master a skill, an individual needs to practice it for 10,000 hours. Gladwell argues that, like hockey, success in computing requires both skill and luck, rather than pure, simple, natural ability. Gladwell's example is situated at the University of Michigan, specifically the new computer center, in 1971. The story of Bill Joy undermines the idea of success as an inexplicable, miraculous accomplishment. Though Gladwell agrees Joy is bright and talented, Joy also lucks into several happy accidents that allow for increased access. These strokes of luck give Joy the opportunity to become a computer expert. Gladwell's use of a psychological study conducted at the Academy of Music in Berlin, Germany, in the early 1990s forms the crux of his argument in this chapter. However, critics have suggested that this study was flawed and that there is no incontrovertible evidence to suggest that doing anything for 10,000 hours guarantees mastery. Rather, practice is, as Gladwell points out elsewhere throughout the text, just one of the factors in success. However, he also correlates the familial and economic advantages necessary to reach 10,000 of practice time, reinforcing the larger thesis of the book.

Gladwell argues that the Beatles and Bill Gates are examples of his notion of time spent directly relating to mastery. While detailing how the Beatles reached the 10,000-hour threshold for mastery, Gladwell also highlights the lucky breaks they had in achieving success, like the connection that landed the band in Hamburg’s music scene. Additionally, while Gates has become something of an American folk hero, Gladwell argues that Gates did not reach his great achievements completely on his own. His wealthy family, his lucky interaction with a computer in 1968, and his college experience allowed him far greater access to opportunity. Without this combination of factors, along with his intelligence and drive, Gates would likely not have become a household name. Again, Gladwell reinforces the idea that success comes not only from being good, but from having no small amount of luck, whether that be time, money, or, in an echo of the hockey player example, birthdate.

Gladwell claims that one important factor of success is the year in which one is born. In terms of wealth, there are 14 Americans, born in a nine-year period of the 1800s, who are among the richest people in history. This suggests that there was some connection to when they were born and the opportunities available to them in terms of innovation and invention, as well as the position they were in to take advantage of the opportunities. Similarly, men born in the same era of Bill Gates were coming of age at the bleeding edge of technology. Proximity to social and technological change, as well as the wealth and connections to take advantage of it, put these men in an advantageous position. Being in the right place at the right time, Gladwell argues, has at least as much to do with success as one's inborn abilities.

Reference

  • “Outliers Chapter 2 Summary & Analysis.” SparkNotes, www.sparknotes.com/lit/outliers/section2/. Accessed 27 Feb. 2023.
]]>
Chapter Two: The 10,000-Hour Rule

Summary: Chapter Two: The 10,000-Hour Rule

Section 1.

Bill Joy, a co-founder of Sun Microsystems, is one of the most influential computer programmers of all time. Joy attended the University of Michigan, thinking to become a biologist or mathematician, but he became obsessed with the Computer Center that opened during his freshman year. In 1975, he enrolled in graduate school at UC Berkeley. At both schools, Bill Joy spent much of his free time programming. After graduating from Berkeley, he founded Sun Microsystems, eventually rewriting the Java programming language. He would appear to be a good example of success based on individual merit.

Section 2.

If achievement is the combination of talent and preparation, how much does innate talent affect one’s success? In the 1990s, a study at Berlin’s elite Academy of Music determined that, regardless of instrument, all of the world-class students had practiced more than 10,000 hours. They did not find anyone at the top level who spent less time, nor did they find anyone who spent that amount of time who was not successful. Neurologist Daniel Levitin states that, across many fields, world-class expertise is never accomplished in less than 10,000 hours. The law holds even for a prodigy like Mozart, who started composing at age six: he did not compose his first masterwork until he was twenty-one. The youth athletes from the previous chapter who made it to the professional level put in 10,000 hours of practice. And note: individuals cannot normally put in that much practice without help. Most people will need supportive parents, financial stability, and probably a special program—like an all-star youth hockey team.

Section 3.

Bill Joy was certainly intelligent, having achieved a perfect score on the math portion of his Scholastic Aptitude Test. His opportunities, however, were extraordinary. Bill Joy happened to choose a college that had a time-sharing computer available, something that was exceedingly rare during the early 1970s. While most students had to pay for computer time, Bill Joy exploited a bug in the college’s system to gain unlimited access to the Computer Center, which was walking distance from where he lived. He was able to spend almost all of his free time programming, and when he went to Berkeley, he had a terminal at home, where he could program until he fell asleep at his keyboard. Bill Joy was able to accumulate 10,000 hours while in college.

Section 4.

The Beatles are another example of the 10,000-hours principle. In 1960, when they were still a high school rock band, they were given the chance to travel to Hamburg, Germany and play in various strip clubs. The Beatles were contracted to play for hours every night, seven nights a week, and thereby were forced to develop as musicians. After a year and a half, they had performed 270 nights. By 1964, when they first found commercial success, they had performed an estimated twelve hundred times—more than most band bands do in an entire career.

Section 5.

Born in Seattle to affluent parents, Bill Gates was sent to a private school for seventh grade. The school’s Mother’s Club funded the purchase of a time-sharing terminal connected to a mainframe computer in Seattle. As an eighth-grader, Gates was able to start programming. When the Mother’s Club could no longer pay for computing time, Gates was able to continue programming at Information Sciences, Inc. (ISI) through a connection he made with one of the school parents. After that, one of ISI’s founders recommended Gates for a programming project at the Bonneville Power station. Gates was able to leave high school during his senior year to program for the Bonneville Power station as an independent study project. By the time Bill Gates dropped out of Harvard, he was well past 10,000 hours of experience.

Section 6.

In a list of the seventy-five richest people in human history, going as far back as ancient Egypt and converting all wealth estimates into modern U.S. dollars, fourteen names are Americans born within nine years of one another (including John D. Rockefeller and J.P. Morgan). What accounts for the fact that a list that covers thousands of years should have 20 percent of its members so close together? The fourteen Americans happened to live during the 1860s and 1870s, when the American economy was undergoing a huge transformation: the expansion of the railroads and the creation of Wall Street. Gladwell argues that the fourteen names are so close in birth date because they were all the perfect age to seize the opportunities available.

Bill Joy and Bill Gates were also born at just the right time. In 1975, Popular Electronics ran a cover story about the Altair 8800, a $397 microcomputer kit. Someone born before 1954 would likely already have a job with IBM, working on mainframes. Someone born after 1956 would likely still be in high school. Most of the biggest pioneers in the modern computer industry, including Bill Gates, Bill Joy, Steve Jobs, and Eric Schmidt, were born in 1954 or 1955, as were Joy’s three fellow founders at Sun.

Analysis: Chapter Two: The 10,000-Hour Rule

Gladwell introduces his controversial and widely disputed 10,000 hours rule. Simply put, the rule suggests that to master a skill, an individual needs to practice it for 10,000 hours. Gladwell argues that, like hockey, success in computing requires both skill and luck, rather than pure, simple, natural ability. Gladwell's example is situated at the University of Michigan, specifically the new computer center, in 1971. The story of Bill Joy undermines the idea of success as an inexplicable, miraculous accomplishment. Though Gladwell agrees Joy is bright and talented, Joy also lucks into several happy accidents that allow for increased access. These strokes of luck give Joy the opportunity to become a computer expert. Gladwell's use of a psychological study conducted at the Academy of Music in Berlin, Germany, in the early 1990s forms the crux of his argument in this chapter. However, critics have suggested that this study was flawed and that there is no incontrovertible evidence to suggest that doing anything for 10,000 hours guarantees mastery. Rather, practice is, as Gladwell points out elsewhere throughout the text, just one of the factors in success. However, he also correlates the familial and economic advantages necessary to reach 10,000 of practice time, reinforcing the larger thesis of the book.

Gladwell argues that the Beatles and Bill Gates are examples of his notion of time spent directly relating to mastery. While detailing how the Beatles reached the 10,000-hour threshold for mastery, Gladwell also highlights the lucky breaks they had in achieving success, like the connection that landed the band in Hamburg’s music scene. Additionally, while Gates has become something of an American folk hero, Gladwell argues that Gates did not reach his great achievements completely on his own. His wealthy family, his lucky interaction with a computer in 1968, and his college experience allowed him far greater access to opportunity. Without this combination of factors, along with his intelligence and drive, Gates would likely not have become a household name. Again, Gladwell reinforces the idea that success comes not only from being good, but from having no small amount of luck, whether that be time, money, or, in an echo of the hockey player example, birthdate.

Gladwell claims that one important factor of success is the year in which one is born. In terms of wealth, there are 14 Americans, born in a nine-year period of the 1800s, who are among the richest people in history. This suggests that there was some connection to when they were born and the opportunities available to them in terms of innovation and invention, as well as the position they were in to take advantage of the opportunities. Similarly, men born in the same era of Bill Gates were coming of age at the bleeding edge of technology. Proximity to social and technological change, as well as the wealth and connections to take advantage of it, put these men in an advantageous position. Being in the right place at the right time, Gladwell argues, has at least as much to do with success as one's inborn abilities.

Reference

  • “Outliers Chapter 2 Summary & Analysis.” SparkNotes, www.sparknotes.com/lit/outliers/section2/. Accessed 27 Feb. 2023.
]]>
<![CDATA[Chapter 3: The Trouble with Geniuses, Part 1]]> https://note.toshiki.dev/save/reading/outliers/3 https://note.toshiki.dev/save/reading/outliers/3 Thu, 01 Jul 2021 00:00:00 GMT Chapter 3: The Trouble with Geniuses, Part 1

Summary: Chapter Three: The Trouble with Geniuses, Part 1

Section 1.

Chris Langan appeared on the television trivia show 1 vs. 100 after being the subject of interviews and at least one documentary, due to his extremely high IQ. He had little difficulty in high school, got a perfect score on his SAT, and read through Principia Mathematica as a teenager. On 1 vs. 100, Langan cashed out with winnings of $250,000.

Section 2.

Shortly after World War I, Lewis Terman, creator of the widely used Stanford-Binet IQ test, became fascinated with child prodigies. In 1921, he identified exceptionally gifted 1,470 students who came to be known as the “Termites.” Terman kept track of them over the years, carefully cataloging their educational achievement, marriages, psychological health, and employment. Terman was sure that the Termites would be the future elite of the United States. The same confidence underlies the use of IQ-like tests, such as the SAT, to assess applicants at Ivy League schools and corporations such as Microsoft and Google. Gladwell states that Terman was wrong about the Termites, and if he had met Chris Langan as a teenager, he would have been wrong about him, too.

Section 3.

Gladwell gives two examples—one easy and one much harder—of questions that use visual puzzles to test IQ, without requiring any language abilities or specific factual knowledge. The average human will score 100. Those scoring below 70 are considered mentally disabled, and those who are successful in graduate programs likely have an IQ of 115 or higher. According to Gladwell, however, above 120 IQ makes little or no difference to success. A similar point applies to basketball: height is certainly an advantage, but there is, at best, modest value in being six foot seven instead of six foot six. A basketball player just needs to be tall enough.

A list of the last twenty-five Americans to win a Nobel Prize in Medicine includes graduates of prestigious schools, such as Columbia, Harvard, and MIT, but also graduates of DePauw, Holy Cross, and Gettysburg College. Similarly, there have been American Nobel laureates in Chemistry from Harvard and MIT, but also from Notre Dame and the University of Illinois. Harvard might have more intelligent students, but many other colleges have students smart enough to win a Nobel.

At the University of Michigan law school, around 10 percent of students are racial minorities. Without affirmative action, there would be less than 3 percent. Looking at career performance after graduation, Michigan found no difference between white and minority graduates. Minority students come into law school with weaker academic credentials than their white counterparts, but they are above the threshold required to be just as successful.

Section 4.

Not all questions that test for intelligence have a single correct answer. A different sort of question might ask for a list of different uses for a brick, or a blanket. A question like this measures imagination and creativity. At a top British high school, one student lists more than ten uses, many of which are comical. Another student, a prodigy with one of the school’s highest IQs, lists just a few uses, all of which are practical. Compared to an IQ test, asking about different uses for a brick might be a better way to identify future Nobel Prize winners.

Section 5.

Terman’s error was using intelligence alone to choose his Termites. While some of the Termites had successful careers, an unexpectedly high went on to careers that even Terman didn’t consider to be successful. The two students tested by Terman’s team who actually did go on to win Nobels were not selected as Termites: their IQs were too low. Terman eventually concluded that “intellect and achievement are far from perfectly correlated.”

Gladwell states that to understand Chris Langan’s prospects of becoming a “true outlier,” one must learn more about him.

Analysis: Chapter Three: The Trouble with Geniuses, Part 1

Intelligence, Gladwell argues, does not equal success. He dedicates this chapter to the examination of geniuses. Comparing the young subjects of Lewis Terman to Chris Langan, Gladwell argues against Terman’s idea that genius is a key to societal advancement. Gladwell lists Langan’s early accomplishments as a shining example of Terman's idea, then swiftly undercuts expectations. Gladwell argues again that individuals do not succeed or fail solely on their own, but rather due to a constellation of factors, many of which are uncontrollable. Langan's early achievements would suggest great things and a continued path toward accomplishment, but Gladwell includes the anecdote of his game show appearance to undermine the notion that genius equals success. Using two questions from an IQ test, Gladwell introduces the idea of an IQ threshold to examine the the larger notion of intelligence and its limitations. Arguing that the measure of someone’s intelligence is only helpful up to a point, Gladwell uses examples of schools that Nobel laureates attended for undergraduate studies. Some, he points out, are elite institutions; others are not. Additionally, he points to success among graduates of the law school at the University of Michigan. There was no quantifiable difference in success post-graduation between white and POC students, some of whom were admitted under affirmative action with slightly lower undergraduate grades and standardized test scores. Reasonably, then, the level of intelligence beyond a certain point is moot. All of the students were intelligent enough to graduate, and beyond that, he argues, their intelligence predicted nothing.

Elements other than intelligence must contribute to success. Gladwell expands on his notion of an intelligence threshold and examines these other factors through an example of a question on a divergence test. Using examples of two students at an elite British school, Gladwell shows that the divergence test has no right answers, but instead looks for answers that demonstrate uniqueness and creativity. Intelligence matters, but so does imagination, creativity, and outside-the-box thinking. Gladwell circles back to Terman, reinforcing that the error when choosing his Termites was a focus on intelligence alone. He once again turns his attention to Chris Langan, foreshadowing that Langan’s story did not follow a direct line to achievement. Intelligence alone does not offer a certain path to success.

Reference

  • “Outliers Chapter 3 Summary & Analysis.” SparkNotes, www.sparknotes.com/lit/outliers/section3/. Accessed 27 Feb. 2023.
]]>
Chapter 3: The Trouble with Geniuses, Part 1

Summary: Chapter Three: The Trouble with Geniuses, Part 1

Section 1.

Chris Langan appeared on the television trivia show 1 vs. 100 after being the subject of interviews and at least one documentary, due to his extremely high IQ. He had little difficulty in high school, got a perfect score on his SAT, and read through Principia Mathematica as a teenager. On 1 vs. 100, Langan cashed out with winnings of $250,000.

Section 2.

Shortly after World War I, Lewis Terman, creator of the widely used Stanford-Binet IQ test, became fascinated with child prodigies. In 1921, he identified exceptionally gifted 1,470 students who came to be known as the “Termites.” Terman kept track of them over the years, carefully cataloging their educational achievement, marriages, psychological health, and employment. Terman was sure that the Termites would be the future elite of the United States. The same confidence underlies the use of IQ-like tests, such as the SAT, to assess applicants at Ivy League schools and corporations such as Microsoft and Google. Gladwell states that Terman was wrong about the Termites, and if he had met Chris Langan as a teenager, he would have been wrong about him, too.

Section 3.

Gladwell gives two examples—one easy and one much harder—of questions that use visual puzzles to test IQ, without requiring any language abilities or specific factual knowledge. The average human will score 100. Those scoring below 70 are considered mentally disabled, and those who are successful in graduate programs likely have an IQ of 115 or higher. According to Gladwell, however, above 120 IQ makes little or no difference to success. A similar point applies to basketball: height is certainly an advantage, but there is, at best, modest value in being six foot seven instead of six foot six. A basketball player just needs to be tall enough.

A list of the last twenty-five Americans to win a Nobel Prize in Medicine includes graduates of prestigious schools, such as Columbia, Harvard, and MIT, but also graduates of DePauw, Holy Cross, and Gettysburg College. Similarly, there have been American Nobel laureates in Chemistry from Harvard and MIT, but also from Notre Dame and the University of Illinois. Harvard might have more intelligent students, but many other colleges have students smart enough to win a Nobel.

At the University of Michigan law school, around 10 percent of students are racial minorities. Without affirmative action, there would be less than 3 percent. Looking at career performance after graduation, Michigan found no difference between white and minority graduates. Minority students come into law school with weaker academic credentials than their white counterparts, but they are above the threshold required to be just as successful.

Section 4.

Not all questions that test for intelligence have a single correct answer. A different sort of question might ask for a list of different uses for a brick, or a blanket. A question like this measures imagination and creativity. At a top British high school, one student lists more than ten uses, many of which are comical. Another student, a prodigy with one of the school’s highest IQs, lists just a few uses, all of which are practical. Compared to an IQ test, asking about different uses for a brick might be a better way to identify future Nobel Prize winners.

Section 5.

Terman’s error was using intelligence alone to choose his Termites. While some of the Termites had successful careers, an unexpectedly high went on to careers that even Terman didn’t consider to be successful. The two students tested by Terman’s team who actually did go on to win Nobels were not selected as Termites: their IQs were too low. Terman eventually concluded that “intellect and achievement are far from perfectly correlated.”

Gladwell states that to understand Chris Langan’s prospects of becoming a “true outlier,” one must learn more about him.

Analysis: Chapter Three: The Trouble with Geniuses, Part 1

Intelligence, Gladwell argues, does not equal success. He dedicates this chapter to the examination of geniuses. Comparing the young subjects of Lewis Terman to Chris Langan, Gladwell argues against Terman’s idea that genius is a key to societal advancement. Gladwell lists Langan’s early accomplishments as a shining example of Terman's idea, then swiftly undercuts expectations. Gladwell argues again that individuals do not succeed or fail solely on their own, but rather due to a constellation of factors, many of which are uncontrollable. Langan's early achievements would suggest great things and a continued path toward accomplishment, but Gladwell includes the anecdote of his game show appearance to undermine the notion that genius equals success. Using two questions from an IQ test, Gladwell introduces the idea of an IQ threshold to examine the the larger notion of intelligence and its limitations. Arguing that the measure of someone’s intelligence is only helpful up to a point, Gladwell uses examples of schools that Nobel laureates attended for undergraduate studies. Some, he points out, are elite institutions; others are not. Additionally, he points to success among graduates of the law school at the University of Michigan. There was no quantifiable difference in success post-graduation between white and POC students, some of whom were admitted under affirmative action with slightly lower undergraduate grades and standardized test scores. Reasonably, then, the level of intelligence beyond a certain point is moot. All of the students were intelligent enough to graduate, and beyond that, he argues, their intelligence predicted nothing.

Elements other than intelligence must contribute to success. Gladwell expands on his notion of an intelligence threshold and examines these other factors through an example of a question on a divergence test. Using examples of two students at an elite British school, Gladwell shows that the divergence test has no right answers, but instead looks for answers that demonstrate uniqueness and creativity. Intelligence matters, but so does imagination, creativity, and outside-the-box thinking. Gladwell circles back to Terman, reinforcing that the error when choosing his Termites was a focus on intelligence alone. He once again turns his attention to Chris Langan, foreshadowing that Langan’s story did not follow a direct line to achievement. Intelligence alone does not offer a certain path to success.

Reference

  • “Outliers Chapter 3 Summary & Analysis.” SparkNotes, www.sparknotes.com/lit/outliers/section3/. Accessed 27 Feb. 2023.
]]>
<![CDATA[Chapter 4: The Trouble with Geniuses, Part 2]]> https://note.toshiki.dev/save/reading/outliers/4 https://note.toshiki.dev/save/reading/outliers/4 Thu, 01 Jul 2021 00:00:00 GMT Chapter 4: The Trouble with Geniuses, Part 2

Summary: Chapter Four: The Trouble with Geniuses, Part 2

Section 1.

Chris Langan’s mother had four children, all from different fathers. Her first husband died in Mexico, the second was murdered, the third committed suicide, and the fourth was an abusive alcoholic. Langan says he has never met someone who grew up as impoverished as he and his brothers did. Attending Reed College, in Oregon, on a scholarship, he felt as though he did not belong with the rest of the students. When his mother neglected to fill out the financial aid forms, he lost his scholarship and dropped out. According to Langan, the school just did not care about their students. Later, Langan attended Montana State University in Bozeman but he dropped out when a dean refused Langan’s request to adjust his class schedule because of car trouble. He still has intellectual interests and has been working on a treatise called the “Cognitive Theoretic Model of the Universe.” When asked if, hypothetically, he would take a position at Harvard, he acknowledges the benefit of an environment with so much intellectual energy, but he worries about a lack of intellectual freedom.

Section 2.

Gladwell points out the oddity of Langan’s experiences. Most colleges, especially small ones, try to accommodate student needs. Smart people take positions at places like Harvard instead of in the private sector precisely for the added intellectual freedom. Gladwell contrasts Langan’s story with Robert Oppenheimer’s. While at Cambridge, Oppenheimer became frustrated with his tutor and tried to poison him. After negotiations with the school administration, Oppenheimer was put on probation and assigned to a psychiatrist. Whereas Langan dropped out after his mother failed to fill out paperwork, Oppenheimer managed to stay in college after trying to kill someone. Later, Oppenheimer convinced General Leslie Groves to make Oppenheimer the scientific director of the Manhattan Project. Oppenheimer had the ability to persuade people, where Langan did not.

Section 3.

Psychologist Robert Sternberg calls the ability to persuade someone “practical intelligence.” It involves knowing what to say, how to say it, and when. It requires an ability to read situations. Individuals can have either practical or analytical intelligence, or in the case of Oppenheimer, both. To understand where one obtains practical intelligence, Gladwell refers to a study conducted by Annette Lareau.

Lareau observed parenting strategies in both Black and white families from different socioeconomic strata. She found two distinct strategies: “concerted cultivation” and “accomplishment of natural growth.” Concerted cultivation, most common in middle-class and wealthier families, is defined by parents’ active promotion of their children’s talents and interests. Accomplishment of natural growth, most common in working-class or impoverished families, is defined by parents’ lack of interest or interaction in their children’s free time. Concerted cultivation, writes Gladwell, encourages children to seek opportunities for growth and to advocate for themselves. Accomplishment of natural growth leaves children unprepared to shape their environment for their own benefit. Concerted cultivation fosters an attitude better suited for success in the modern world.

Section 4.

Oppenheimer was raised by affluent parents who sent him to a progressive private school and took an active interest in his hobbies.

  • Affluent: Having an abundant supply of money or possessions of value.

By contrast, Chris Langan’s brother Mark states that as children, they learned to resent authority. Mark, too, was unable to obtain financial aid, because he had no knowledge of how the system worked. If Chris Langan had been raised in a family that valued education, he probably would have had more success.

Section 5.

Once the Termites reached working adulthood, Terman grouped 730 of the males into three categories, based on their levels of success. The top 20 percent were upper-class professionals, while the bottom 20 percent had low-paying jobs or were unemployed. After analyzing the differences between the groups, Terman found that the bottom 20 percent came almost entirely from the lowest social and economic classes. What they lacked was “a community around them that prepared them properly for the world.”

Section 6.

Chris Langan lives on a horse farm in Missouri, where he still writes. He is happily married and continues to read physics and philosophy. While he has spent decades on his writing, almost none of it has ever been published. Langan admits he has not tried to contact publishers or found an agent—and does not plan to. Chris Langan did not have the support necessary to meet success. Gladwell points that no one ever makes it alone, regardless of if they are successful musicians, athletes, tech billionaires, or geniuses.

Analysis: Chapter Four: The Trouble with Geniuses, Part 2

Family background plays a crucial role in an individual’s success. While a genius like Chris Langan should thrive on a college campus, he drops out. Langan doesn’t struggle with academics, but with paperwork, procedures, and environment. Gladwell’s characterization of Langan almost makes him seem like two separate characters: a confident, genius game show contestant versus a child from a poor and troubled family. Langan may be a true outlier in the sense that he doesn’t seem to fit in academia or the working-class world.  Langan’s story is ironic. His brilliant mind should propel him to success. However, his story also perfectly proves Gladwell’s point that brainpower alone does not lead to success. The author delves deeper into the irony of Langan’s situation by comparing him to Robert Oppenheimer, who worked on the nuclear bomb during World War II. Like Langan, Oppenheimer possesses great intelligence. Unlike Langan, Oppenheimer has an understanding that allows him to navigate the world effectively. Oppenheimer knows how to combat challenges, where Langan gets bested by a financial aid problem and class schedule. Oppenheimer’s family background gave him the confidence to deal with authority while Langan’s upbringing created a distrust of authority. Without a family background that encourages success, intelligence is not enough.

Contrast & Comparison

Oppenheimer’s family background gave him the confidence to deal with authority while Langan’s upbringing created a distrust of authority.

The power of persuasion is an important factor that drives success. Gladwell notes that the power of persuasion is practical intelligence. He contrasts practical intelligence with analytical ability, noting that just because a person is smart does not mean they have practical intelligence. These two types of knowledge are not necessarily coeval. He reinforces this point with a return to the comparison of Langan and Oppenheimer. Both men are exceedingly intelligent, but Langan lacks the social savvy of practical intelligence. Gladwell suggests that individuals gain practical intelligence skills from their families, discussing a study by sociologist Annette Lareau to prove his point. Children from wealthier families learn how to interact with society in a way that drives achievement. Successful people have the power of persuasion and can convince others to see things from their point of view.

Success, then, depends on more than individual effort. Gladwell builds this argument by detailing the differences between Oppenheimer’s upbringing and Langan’s. Oppenheimer lived in an upper-class neighborhood with myriad advantages. He learned how to negotiate and stand up for himself. Langan’s family moved from place to place, struggling for jobs, money, food, and clothes, and Langan learned that he couldn’t rely on others. Gladwell's consideration of the Termites' success or struggles as adults supports his assertion that success is more than an individual effort; Gladwell states, “In the end, only one thing mattered: family background.” Terman’s findings and Gladwell’s conclusion do not mean that talented individuals from lower social and economic classes cannot have successful futures. To succeed, everyone needs help along the way, if not from family, then from a supportive community. Individuals do not achieve success solely on their own.

Reference

  • “Outliers Chapter 4 Summary & Analysis.” SparkNotes, www.sparknotes.com/lit/outliers/section4/.
]]>
Chapter 4: The Trouble with Geniuses, Part 2

Summary: Chapter Four: The Trouble with Geniuses, Part 2

Section 1.

Chris Langan’s mother had four children, all from different fathers. Her first husband died in Mexico, the second was murdered, the third committed suicide, and the fourth was an abusive alcoholic. Langan says he has never met someone who grew up as impoverished as he and his brothers did. Attending Reed College, in Oregon, on a scholarship, he felt as though he did not belong with the rest of the students. When his mother neglected to fill out the financial aid forms, he lost his scholarship and dropped out. According to Langan, the school just did not care about their students. Later, Langan attended Montana State University in Bozeman but he dropped out when a dean refused Langan’s request to adjust his class schedule because of car trouble. He still has intellectual interests and has been working on a treatise called the “Cognitive Theoretic Model of the Universe.” When asked if, hypothetically, he would take a position at Harvard, he acknowledges the benefit of an environment with so much intellectual energy, but he worries about a lack of intellectual freedom.

Section 2.

Gladwell points out the oddity of Langan’s experiences. Most colleges, especially small ones, try to accommodate student needs. Smart people take positions at places like Harvard instead of in the private sector precisely for the added intellectual freedom. Gladwell contrasts Langan’s story with Robert Oppenheimer’s. While at Cambridge, Oppenheimer became frustrated with his tutor and tried to poison him. After negotiations with the school administration, Oppenheimer was put on probation and assigned to a psychiatrist. Whereas Langan dropped out after his mother failed to fill out paperwork, Oppenheimer managed to stay in college after trying to kill someone. Later, Oppenheimer convinced General Leslie Groves to make Oppenheimer the scientific director of the Manhattan Project. Oppenheimer had the ability to persuade people, where Langan did not.

Section 3.

Psychologist Robert Sternberg calls the ability to persuade someone “practical intelligence.” It involves knowing what to say, how to say it, and when. It requires an ability to read situations. Individuals can have either practical or analytical intelligence, or in the case of Oppenheimer, both. To understand where one obtains practical intelligence, Gladwell refers to a study conducted by Annette Lareau.

Lareau observed parenting strategies in both Black and white families from different socioeconomic strata. She found two distinct strategies: “concerted cultivation” and “accomplishment of natural growth.” Concerted cultivation, most common in middle-class and wealthier families, is defined by parents’ active promotion of their children’s talents and interests. Accomplishment of natural growth, most common in working-class or impoverished families, is defined by parents’ lack of interest or interaction in their children’s free time. Concerted cultivation, writes Gladwell, encourages children to seek opportunities for growth and to advocate for themselves. Accomplishment of natural growth leaves children unprepared to shape their environment for their own benefit. Concerted cultivation fosters an attitude better suited for success in the modern world.

Section 4.

Oppenheimer was raised by affluent parents who sent him to a progressive private school and took an active interest in his hobbies.

  • Affluent: Having an abundant supply of money or possessions of value.

By contrast, Chris Langan’s brother Mark states that as children, they learned to resent authority. Mark, too, was unable to obtain financial aid, because he had no knowledge of how the system worked. If Chris Langan had been raised in a family that valued education, he probably would have had more success.

Section 5.

Once the Termites reached working adulthood, Terman grouped 730 of the males into three categories, based on their levels of success. The top 20 percent were upper-class professionals, while the bottom 20 percent had low-paying jobs or were unemployed. After analyzing the differences between the groups, Terman found that the bottom 20 percent came almost entirely from the lowest social and economic classes. What they lacked was “a community around them that prepared them properly for the world.”

Section 6.

Chris Langan lives on a horse farm in Missouri, where he still writes. He is happily married and continues to read physics and philosophy. While he has spent decades on his writing, almost none of it has ever been published. Langan admits he has not tried to contact publishers or found an agent—and does not plan to. Chris Langan did not have the support necessary to meet success. Gladwell points that no one ever makes it alone, regardless of if they are successful musicians, athletes, tech billionaires, or geniuses.

Analysis: Chapter Four: The Trouble with Geniuses, Part 2

Family background plays a crucial role in an individual’s success. While a genius like Chris Langan should thrive on a college campus, he drops out. Langan doesn’t struggle with academics, but with paperwork, procedures, and environment. Gladwell’s characterization of Langan almost makes him seem like two separate characters: a confident, genius game show contestant versus a child from a poor and troubled family. Langan may be a true outlier in the sense that he doesn’t seem to fit in academia or the working-class world.  Langan’s story is ironic. His brilliant mind should propel him to success. However, his story also perfectly proves Gladwell’s point that brainpower alone does not lead to success. The author delves deeper into the irony of Langan’s situation by comparing him to Robert Oppenheimer, who worked on the nuclear bomb during World War II. Like Langan, Oppenheimer possesses great intelligence. Unlike Langan, Oppenheimer has an understanding that allows him to navigate the world effectively. Oppenheimer knows how to combat challenges, where Langan gets bested by a financial aid problem and class schedule. Oppenheimer’s family background gave him the confidence to deal with authority while Langan’s upbringing created a distrust of authority. Without a family background that encourages success, intelligence is not enough.

Contrast & Comparison

Oppenheimer’s family background gave him the confidence to deal with authority while Langan’s upbringing created a distrust of authority.

The power of persuasion is an important factor that drives success. Gladwell notes that the power of persuasion is practical intelligence. He contrasts practical intelligence with analytical ability, noting that just because a person is smart does not mean they have practical intelligence. These two types of knowledge are not necessarily coeval. He reinforces this point with a return to the comparison of Langan and Oppenheimer. Both men are exceedingly intelligent, but Langan lacks the social savvy of practical intelligence. Gladwell suggests that individuals gain practical intelligence skills from their families, discussing a study by sociologist Annette Lareau to prove his point. Children from wealthier families learn how to interact with society in a way that drives achievement. Successful people have the power of persuasion and can convince others to see things from their point of view.

Success, then, depends on more than individual effort. Gladwell builds this argument by detailing the differences between Oppenheimer’s upbringing and Langan’s. Oppenheimer lived in an upper-class neighborhood with myriad advantages. He learned how to negotiate and stand up for himself. Langan’s family moved from place to place, struggling for jobs, money, food, and clothes, and Langan learned that he couldn’t rely on others. Gladwell's consideration of the Termites' success or struggles as adults supports his assertion that success is more than an individual effort; Gladwell states, “In the end, only one thing mattered: family background.” Terman’s findings and Gladwell’s conclusion do not mean that talented individuals from lower social and economic classes cannot have successful futures. To succeed, everyone needs help along the way, if not from family, then from a supportive community. Individuals do not achieve success solely on their own.

Reference

  • “Outliers Chapter 4 Summary & Analysis.” SparkNotes, www.sparknotes.com/lit/outliers/section4/.
]]>