python コピー
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
# OFA の 3 つの「縮め方」を、1 つの層と 1 つのユニットで書いたもの(論文の 3.3 節)。
class ElasticDepthwiseConv(nn.Module):
"""可変のカーネル:7×7 の中心を 5×5・3×3 として使い、変換行列を掛ける(図 5 左)"""
def __init__(self, channels, max_kernel=7):
super().__init__()
self.weight = nn.Parameter(torch.randn(channels, 1, max_kernel, max_kernel) * 0.1)
# 層ごとの変換行列(チャネルの間で共有)。25×25 + 9×9 = 706 個の追加パラメータ
# 初期値は単位行列(例。論文に初期値の記載はない)
self.T5 = nn.Parameter(torch.eye(25))
self.T3 = nn.Parameter(torch.eye(9))
self.kernel = max_kernel
def get_kernel(self, k):
w = self.weight # (C, 1, 7, 7)
if k <= 5:
w = w[:, :, 1:6, 1:6].reshape(-1, 25) @ self.T5 # 中心の 5×5 に変換行列を掛ける
w = w.reshape(-1, 1, 5, 5)
if k == 3:
w = w[:, :, 1:4, 1:4].reshape(-1, 9) @ self.T3 # さらに中心の 3×3
w = w.reshape(-1, 1, 3, 3)
return w
def forward(self, x, active_channels=None):
w = self.get_kernel(self.kernel)
if active_channels is not None:
w = w[:active_channels] # 幅を縮めたとき
return F.conv2d(x, w, padding=self.kernel // 2, groups=w.shape[0])
class ElasticBlock(nn.Module):
"""1 × 1 で広げる → 深さ方向の畳み込み → 1 × 1 で戻す(MobileNetV3 型の層を簡単にしたもの)"""
def __init__(self, c, max_expand=6):
super().__init__()
self.hidden = c * max_expand
self.expand = nn.Conv2d(c, self.hidden, 1, bias=False)
self.dw = ElasticDepthwiseConv(self.hidden)
self.project = nn.Conv2d(self.hidden, c, 1, bias=False)
self.expand_ratio, self.c = max_expand, c
@torch.no_grad()
def sort_channels(self):
"""可変の幅:中間のチャネルを重みの L1 ノルムの大きい順に並べ替える(図 6)"""
# 各チャネルの重みの L1 ノルム(どの重みで測るかはここでは例として 1×1 の戻しの重みを使う)
importance = self.project.weight.abs().sum(dim=(0, 2, 3))
idx = importance.argsort(descending=True)
self.expand.weight.copy_(self.expand.weight[idx])
self.dw.weight.copy_(self.dw.weight[idx])
self.project.weight.copy_(self.project.weight[:, idx]) # 並べ替えても出力は変わらない
def forward(self, x):
n = self.c * self.expand_ratio # 上位 n チャネルだけ使う
h = F.conv2d(x, self.expand.weight[:n]).relu()
h = self.dw(h, active_channels=n).relu()
return x + F.conv2d(h, self.project.weight[:, :n])
class ElasticUnit(nn.Module):
"""可変の深さ:最初の D 層だけを使い、後ろを飛ばす(図 5 右)"""
def __init__(self, c, max_depth=4):
super().__init__()
self.blocks = nn.ModuleList(ElasticBlock(c) for _ in range(max_depth))
self.depth = max_depth
def forward(self, x):
for block in self.blocks[: self.depth]:
x = block(x)
return x
def sample_subnet(unit, kernels, depths, ratios):
unit.depth = random.choice(depths)
for b in unit.blocks:
b.dw.kernel = random.choice(kernels)
b.expand_ratio = random.choice(ratios)
# 段階的な縮小:選べる値を大きいものから順に増やしていく(付録 B)
unit = ElasticUnit(c=16)
opt = torch.optim.SGD(unit.parameters(), lr=0.01, momentum=0.9, nesterov=True)
stages = [
dict(kernels=[7], depths=[4], ratios=[6], n_sub=1), # 最大のネットワーク
dict(kernels=[7, 5, 3], depths=[4], ratios=[6], n_sub=1), # ① 可変のカーネル
dict(kernels=[7, 5, 3], depths=[4, 3, 2], ratios=[6], n_sub=2), # ② 可変の深さ
dict(kernels=[7, 5, 3], depths=[4, 3, 2], ratios=[6, 4, 3], n_sub=4), # ③ 可変の幅
]
for s in stages:
if s["ratios"] != [6]:
for b in unit.blocks:
b.sort_channels() # 幅を縮める前に並べ替える
for step in range(3): # 実際は数十〜百数十エポック
x = torch.randn(2, 16, random.choice([16, 20, 24]), 24) # 解像度もバッチごとに変える
opt.zero_grad()
for _ in range(s["n_sub"]): # 複数のサブネットワークの勾配を合わせる
sample_subnet(unit, s["kernels"], s["depths"], s["ratios"])
unit(x).pow(2).mean().backward() # 実際は分類の損失+最大のネットワークからの蒸留
opt.step()
print("学習の手順を確認しました")