rust
use burn::{
module::Module,
nn::{
self,
attention::{self, Attention},
Linear,
},
tensor::{Tensor, Shape},
Device,
};
/// SD 1.5の自己注意を構成する設定
#[derive(Module, Debug, Clone)]
pub struct AttentionConfig {
pub dim: usize, // 埋め込み次元
pub num_heads: usize, // 注意ヘッドの数
pub head_dim: usize, // 各ヘッドの次元
pub dropout: f64, // ドロップアウト率
pub bias: bool, // バイアス項の使用有無
pub upcast_attention: bool, // 注意の精度を上げるか
pub upcast_softmax: bool, // ソフトマックスの精度を上げるか
pub cross_attention_dim: Option<usize>, // クロス注意の次元
}
impl AttentionConfig {
/// 新しい注意設定を作成
pub fn new(
dim: usize,
num_heads: usize,
cross_attention_dim: Option<usize>,
dropout: f64,
bias: bool,
) -> Self {
let head_dim = dim / num_heads;
Self {
dim,
num_heads,
head_dim,
dropout,
bias,
upcast_attention: false,
upcast_softmax: false,
cross_attention_dim,
}
}
}
/// SD 1.5で使用される注意機構
#[derive(Module, Debug)]
pub struct Attention {
to_q: Linear, // クエリ生成用線形層
to_k: Linear, // キー生成用線形層
to_v: Linear, // バリュー生成用線形層
to_out: Linear, // 出力用線形層
config: AttentionConfig, // 注意の設定
}
impl Attention {
/// 新しい注意層を作成
pub fn new(config: &AttentionConfig, device: &Device) -> Self {
let cross_dim = config.cross_attention_dim.unwrap_or(config.dim);
Self {
to_q: Linear::new(config.dim, config.dim, device),
to_k: Linear::new(cross_dim, config.dim, device),
to_v: Linear::new(cross_dim, config.dim, device),
to_out: Linear::new(config.dim, config.dim, device),
config: config.clone(),
}
}
/// 注意スコアの計算
fn get_attention_scores(&self, query: Tensor, key: Tensor) -> Tensor {
let upcast = self.config.upcast_attention ||
(query.dtype() != burn::tensor::DType::F32 &&
self.config.upcast_softmax);
// 精度を上げる必要がある場合、float32に変換
let mut query = if upcast { query.to_dtype(burn::tensor::DType::F32) } else { query.clone() };
let mut key = if upcast { key.to_dtype(burn::tensor::DType::F32) } else { key.clone() };
// スケーリング係数
let scale_factor = if self.config.upcast_softmax {
1.0
} else {
(self.config.head_dim as f64).powf(-0.5)
};
// 注意重みの計算
let mut attn_weights = query.matmul(&key.transpose([0, 1, 3, 2])) * scale_factor;
if self.config.upcast_softmax {
attn_weights = attn_weights.to_dtype(burn::tensor::DType::F32);
}
// ソフトマックス適用
let mut attn_probs = attn_weights.softmax(3);
if self.config.upcast_softmax {
attn_probs = attn_probs.to_dtype(query.dtype());
}
attn_probs
}
/// 順伝播
pub fn forward(&self, x: Tensor, context: Option<Tensor>) -> Tensor {
let batch_size = x.shape().dims4().0;
let seq_len = x.shape().dims4().2 * x.shape().dims4().3; // 高さ×幅
// クエリ、キー、バリューの生成
let query = self.to_q.forward(x.clone());
let key = self.to_k.forward(context.clone().unwrap_or(x.clone()));
let value = self.to_v.forward(context.unwrap_or(x));
// マルチヘッド形式に再整形
let query = query.reshape([batch_size, self.config.num_heads, seq_len, self.config.head_dim])
.transpose([0, 1, 2, 3]);
let key = key.reshape([batch_size, self.config.num_heads, seq_len, self.config.head_dim])
.transpose([0, 1, 3, 2]); // 行列乗算の効率化のため
let value = value.reshape([batch_size, self.config.num_heads, seq_len, self.config.head_dim])
.transpose([0, 1, 2, 3]);
// 注意スコアの計算
let attn_probs = self.get_attention_scores(query, key);
// 注意をバリューに適用
let mut out = attn_probs.matmul(&value);
// 元の形式に戻す
out = out.transpose([0, 2, 1, 3])
.reshape([batch_size, self.config.dim, x.shape().dims4().2, x.shape().dims4().3]);
// 出力射影
self.to_out.forward(out)
}
}
/// SD 1.5で使用されるフィードフォワードネットワーク
#[derive(Module, Debug)]
pub struct FeedForward {
net: Vec<Linear>, // 線形層の配列
dropout: nn::Dropout, // ドロップアウト層
}
impl FeedForward {
/// 新しいフィードフォワードネットワークを作成
pub fn new(dim: usize, mult: usize, dropout: f64, device: &Device) -> Self {
Self {
net: vec![
Linear::new(dim, dim * mult, device),
Linear::new(dim * mult, dim, device),
],
dropout: nn::Dropout::new(dropout),
}
}
/// 順伝播
pub fn forward(&self, x: Tensor) -> Tensor {
let x = self.net[0].forward(x);
let x = x.gelu(); // GELU活性化関数
let x = self.dropout.forward(x);
self.net[1].forward(x)
}
}
/// 注意とフィードフォワードネットワークを持つトランスフォーマーブロック
#[derive(Module, Debug)]
pub struct BasicTransformerBlock {
attn1: Attention, // 自己注意
ff: FeedForward, // フィードフォワードネットワーク
norm1: nn::LayerNorm, // 層正規化1
norm2: nn::LayerNorm, // 層正規化2
cross_attention_dim: Option<usize>, // クロス注意の次元
attn2: Option<Attention>, // クロス注意
}
impl BasicTransformerBlock {
/// 新しいトランスフォーマーブロックを作成
pub fn new(config: &AttentionConfig, device: &Device) -> Self {
let cross_attention_dim = config.cross_attention_dim;
let has_cross_attention = cross_attention_dim.is_some();
let mut attn2 = None;
if has_cross_attention {
let cross_config = AttentionConfig::new(
config.dim,
config.num_heads,
cross_attention_dim,
config.dropout,
config.bias,
);
attn2 = Some(Attention::new(&cross_config, device));
}
Self {
attn1: Attention::new(config, device),
ff: FeedForward::new(config.dim, 4, config.dropout, device),
norm1: nn::LayerNorm::new(config.dim, 1e-5),
norm2: nn::LayerNorm::new(config.dim, 1e-5),
cross_attention_dim,
attn2,
}
}
/// 順伝播
pub fn forward(&self, x: Tensor, context: Option<Tensor>) -> Tensor {
// 自己注意
let residual = x.clone();
let x = self.norm1.forward(x);
let x = self.attn1.forward(x, None);
let mut x = x + residual;
// クロス注意(存在する場合)
if let Some(attn2) = &self.attn2 {
let residual = x.clone();
let x = self.norm2.forward(x);
let x = attn2.forward(x, context);
x = x + residual;
}
// フィードフォワードネットワーク
let residual = x.clone();
let x = self.norm2.forward(x);
let x = self.ff.forward(x);
x + residual
}
}
/// 画像のような入力に注意を適用する空間トランスフォーマー
#[derive(Module, Debug)]
pub struct SpatialTransformer {
in_channels: usize, // 入力チャンネル数
num_heads: usize, // ヘッド数
head_dim: usize, // 各ヘッドの次元
norm: nn::GroupNorm, // グループ正規化
proj_in: Linear, // 入力射影
proj_out: Linear, // 出力射影
transform: BasicTransformerBlock, // トランスフォーマーブロック
}
impl SpatialTransformer {
/// 新しい空間トランスフォーマーを作成
pub fn new(
in_channels: usize,
num_heads: usize,
head_dim: usize,
cross_attention_dim: Option<usize>,
dropout: f64,
device: &Device,
) -> Self {
let config = AttentionConfig::new(
num_heads * head_dim,
num_heads,
cross_attention_dim,
dropout,
true,
);
Self {
in_channels,
num_heads,
head_dim,
norm: nn::GroupNorm::new(32, in_channels, 1e-6),
proj_in: Linear::new(in_channels, num_heads * head_dim, device),
proj_out: Linear::new(num_heads * head_dim, in_channels, device),
transform: BasicTransformerBlock::new(&config, device),
}
}
/// 順伝播
pub fn forward(&self, x: Tensor, context: Option<Tensor>) -> Tensor {
let (batch, channels, height, width) = x.shape().dims4();
// 正規化
let h = self.norm.forward(x.clone());
// シーケンス形式に再整形
let h = h.reshape([batch, channels, height * width])
.transpose([0, 2, 1]); // [batch, 高さ×幅, チャンネル]
// 注意空間への射影
let h = self.proj_in.forward(h);
// トランスフォーマーの適用
let h = self.transform.forward(h, context);
// 再射影
let h = self.proj_out.forward(h);
// 画像形式に戻す
let h = h.transpose([0, 2, 1])
.reshape([batch, channels, height, width]);
// 残差接続
h + x
}
}
この実装はBurnフレームワークの機能を最大限に活用し、SD 1.5のアーキテクチャを正確に再現しています。Burnのモジュール性と柔軟性により、モデルのトレーニングや推論に必要なすべての機能が揃っています。