python
import torch
import torch.nn as nn
"""
NASNet の探索空間のセルを、構造(genotype)から組み立てる例。
1つのブロック = (入力1, 入力2, 操作1, 操作2, 合わせ方)。セルの入力は 0 = h_{i-1}, 1 = h_i、
2 以降は前のブロックで作った隠れ状態。使われなかった隠れ状態を連結してセルの出力にする。
(下の GENOTYPE は説明用の例で、論文の NASNet-A そのものではない)
学習済みの NASNet-A は timm にある:timm.create_model('nasnetalarge', pretrained=True)
"""
class SepConv(nn.Module):
"""分離畳み込み。論文の付録 A.4 に従い、ReLU → 畳み込み → BN の順で 2 回かける"""
def __init__(self, C, k):
super().__init__()
layers = []
for _ in range(2):
layers += [nn.ReLU(), nn.Conv2d(C, C, k, padding=k // 2, groups=C, bias=False),
nn.Conv2d(C, C, 1, bias=False), nn.BatchNorm2d(C)]
self.op = nn.Sequential(*layers)
def forward(self, x):
return self.op(x)
OPS = {
'identity': lambda C: nn.Identity(),
'sep_3x3': lambda C: SepConv(C, 3),
'sep_5x5': lambda C: SepConv(C, 5),
'sep_7x7': lambda C: SepConv(C, 7),
'avg_3x3': lambda C: nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False),
'max_3x3': lambda C: nn.MaxPool2d(3, stride=1, padding=1),
}
# (入力1, 入力2, 操作1, 操作2, 合わせ方) × B = 5 ブロック(説明用の例)
GENOTYPE = [
(0, 1, 'sep_3x3', 'avg_3x3', 'add'),
(1, 1, 'sep_5x5', 'identity', 'add'),
(0, 2, 'max_3x3', 'sep_3x3', 'add'),
(3, 1, 'avg_3x3', 'sep_7x7', 'add'),
(0, 4, 'identity', 'avg_3x3', 'add'),
]
class DropPath(nn.Module):
"""学習中だけ、経路(1つの操作の出力)をサンプルごとに確率 p で 0 にする"""
def __init__(self):
super().__init__()
self.p = 0.0 # ScheduledDropPath:学習の進みに合わせて外から線形に増やす
def forward(self, x):
if not self.training or self.p == 0.0:
return x # model.eval() では何もしない
keep = 1.0 - self.p
mask = torch.bernoulli(torch.full((x.size(0), 1, 1, 1), keep, device=x.device))
return x * mask / keep
class Cell(nn.Module):
def __init__(self, C, genotype=GENOTYPE):
super().__init__()
self.genotype = genotype
self.ops = nn.ModuleList()
self.drops = nn.ModuleList()
for i1, i2, op1, op2, _ in genotype:
self.ops.append(nn.ModuleList([OPS[op1](C), OPS[op2](C)]))
self.drops.append(nn.ModuleList([DropPath(), DropPath()]))
used = {i for i1, i2, *_ in genotype for i in (i1, i2)}
self.outputs = [i for i in range(2, 2 + len(genotype)) if i not in used] # 使われなかった隠れ状態
def forward(self, h_prev, h):
states = [h_prev, h]
for (i1, i2, _, _, comb), (o1, o2), (d1, d2) in zip(self.genotype, self.ops, self.drops):
a, b = d1(o1(states[i1])), d2(o2(states[i2]))
states.append(a + b if comb == 'add' else torch.cat([a, b], dim=1))
return torch.cat([states[i] for i in self.outputs], dim=1)
def set_drop_path(model, step, total_steps, final_p=0.3):
"""ScheduledDropPath:落とす確率を 0 から final_p まで線形に増やす(final_p は例)"""
for m in model.modules():
if isinstance(m, DropPath):
m.p = final_p * step / total_steps
cell = Cell(C=16)
h_prev = torch.randn(2, 16, 32, 32)
h = torch.randn(2, 16, 32, 32)
cell.train()
set_drop_path(cell, step=500, total_steps=1000)
out = cell(h_prev, h)
print(cell.outputs, out.shape) # 使われなかった隠れ状態の番号と、連結した出力の形