rust-candle学习笔记11-实现一个简单的自注意力

参考:about-pytorch

定义ScaledDotProductAttention结构体:

rust 复制代码
use candle_core::{Result, Device, Tensor};
use candle_nn::{Linear, Module, linear_no_bias, VarMap, VarBuilder, ops};

struct ScaledDotProductAttention {
    wq: Linear,
    wk: Linear,
    wv: Linear,
    d_model: Tensor,
    device: Device,
}

为ScaledDotProductAttention结构体实现new方法:

rust 复制代码
impl ScaledDotProductAttention {
    fn new(vb: VarBuilder, embedding_dim: usize, out_dim: usize, device: Device) -> Result<Self> {
        Ok(Self { 
            wq: linear_no_bias(embedding_dim, out_dim, vb.pp("wq"))?, 
            wk: linear_no_bias(embedding_dim, out_dim, vb.pp("wk"))?, 
            wv: linear_no_bias(embedding_dim, out_dim, vb.pp("wv"))?,
            d_model: Tensor::new(embedding_dim as f32, &device)?,
            device,
        })
    }
}

为结构体实现Module的forward trait:

rust 复制代码
impl Module for ScaledDotProductAttention {
    fn forward(&self, xs: &Tensor) -> Result<Tensor> {
        let q = self.wq.forward(xs)?;
        let k = self.wk.forward(xs)?;
        let v = self.wv.forward(xs)?;
        let attn_score = q.matmul(&k.t()?)?;
        let attn_score = attn_score.broadcast_div(&self.d_model.sqrt()?)?;
        let dim = attn_score.rank() - 1;
        let attn_weights = ops::softmax(&attn_score, dim)?;
        let attn_output = attn_weights.matmul(&v)?;
        Ok(attn_output)
    }
}

融合qkv实现:

定义ScaledDotProductAttentionFusedQKV结构体:

rust 复制代码
struct ScaledDotProductAttentionFusedQKV {
    w_qkv: Linear,
    d_model: Tensor,
    device: Device,
}

为结构体实现new方法:

rust 复制代码
impl ScaledDotProductAttentionFusedQKV {
    fn new(vb: VarBuilder, embedding_dim: usize, out_dim: usize, device: Device) -> Result<Self> {
        Ok(Self { 
            w_qkv: linear_no_bias(embedding_dim, 3*out_dim, vb.pp("w_qkv"))?,
            d_model: Tensor::new(embedding_dim as f32, &device)?,
            device,
        })
    }
}

为结构体实现forward trait:

rust 复制代码
impl Module for ScaledDotProductAttentionFusedQKV {
    fn forward(&self, xs: &Tensor) -> Result<Tensor> {
        let qkv = self.w_qkv.forward(xs)?;
        let (batch_size, seq_len, _) = qkv.dims3()?;
        let qkv = qkv.reshape((batch_size, seq_len, 3, ()))?;
        let q = qkv.get_on_dim(2, 0)?;
        let q = q.reshape((batch_size, seq_len, ()))?;
        let k = qkv.get_on_dim(2, 1)?;
        let k = k.reshape((batch_size, seq_len, ()))?;
        let v = qkv.get_on_dim(2, 2)?;
        let v = v.reshape((batch_size, seq_len, ()))?;
        let attn_score = q.matmul(&k.t()?)?;
        let attn_score = attn_score.broadcast_div(&self.d_model.sqrt()?)?;
        let dim = attn_score.rank() - 1;
        let attn_weights = ops::softmax(&attn_score, dim)?;
        let attn_output = attn_weights.matmul(&v)?;
        Ok(attn_output)
    }
}

测试:

rust 复制代码
fn main() -> Result<()> {
    let device = Device::cuda_if_available(0)?;
    let varmap = VarMap::new();
    let vb = VarBuilder::from_varmap(&varmap, candle_core::DType::F32, &device);
    
    let input = Tensor::from_vec(vec![0.43f32, 0.15, 0.89, 
                                                    0.55, 0.87, 0.66,
                                                    0.57, 0.85, 0.64,
                                                    0.22, 0.58, 0.33,
                                                    0.77, 0.25, 0.10,
                                                    0.05, 0.80, 0.55, 
                                                    0.43, 0.15, 0.89, 
                                                    0.55, 0.87, 0.66,
                                                    0.57, 0.85, 0.64,
                                                    0.22, 0.58, 0.33,
                                                    0.77, 0.25, 0.10,
                                                    0.05, 0.80, 0.55], (2, 6, 3), &device)?;
    // let model = ScaledDotProductAttention::new(vb.clone(), 3, 2, device.clone())?;
    let model = ScaledDotProductAttentionFusedQKV::new(vb.clone(), 3, 2, device.clone())?;
    let output = model.forward(&input)?;
    println!("output: {:?}\n", output);
    println!("output: {:?}\n", output.to_vec3::<f32>()?);
    Ok(())
}
相关推荐
夕除1 小时前
Redis 过期策略
redis·笔记·面试
Nuanyt3 小时前
Agent 学习笔记(下篇三):上线工程、进阶选择与操作界面(Stage 7 / 7.5 / 8 + 延伸路线)
笔记·python·学习·memory·aiagent·harness
叼烟扛炮4 小时前
Linux 学习笔记(四十一):TCP 并发演进——从单进程到多线程服务器
linux·运维·服务器·网络·笔记·学习·tcp/ip
叼烟扛炮4 小时前
Linux 学习笔记(四十四):HTTP 协议解析与极简 Web 服务器实战
linux·服务器·学习
叼烟扛炮5 小时前
Linux 学习笔记(四十三):网络编程进阶——自定义协议解决 TCP 粘包与守护进程
linux·开发语言·网络·笔记·tcp/ip
songyuc5 小时前
【Manskill3】TableSceneBuilder学习笔记
pytorch·笔记·学习
外收内放6 小时前
Python基础语法练习题(75)
开发语言·python·学习
゛凌乱的记忆づ7 小时前
好用的md文件编辑器——TyporaS与Typora
笔记·git·typora·markdown
怪我冷i7 小时前
Rust 的impl语法详解
开发语言·后端·rust
kyrie_sakura8 小时前
大模型学习20 大模型学习 - LangChain3 - Agents
人工智能·学习·langchain