use super::Module;
use crate::tensor::Tensor;
use crate::Device;
pub struct Embedding {
pub weight: Tensor,
pub vocab_size: usize,
pub embedding_dim: usize,
}
impl Embedding {
pub fn new(vocab_size: usize, embedding_dim: usize, device: &Device) -> Self {
let weight = Tensor::randn(&[vocab_size, embedding_dim], device)
.mul_scalar(0.02)
.requires_grad_();
Self {
weight,
vocab_size,
embedding_dim,
}
}
pub fn from_weights(weight: Tensor) -> Self {
let vocab_size = weight.shape[0];
let embedding_dim = weight.shape[1];
Self {
weight,
vocab_size,
embedding_dim,
}
}
pub fn forward_ids(&self, ids: &[usize]) -> Tensor {
crate::functional::embedding(&self.weight, ids)
}
pub fn forward_indices(&self, token_ids: &[u32]) -> Tensor {
let ids: Vec<usize> = token_ids.iter().map(|&id| id as usize).collect();
self.forward_ids(&ids)
}
}
impl Module for Embedding {
fn forward(&self, x: &Tensor) -> Tensor {
let ids: Vec<usize> = x.to_vec().iter().map(|&v| v as usize).collect();
let out_shape = [&x.shape[..], &[self.embedding_dim]].concat();
self.forward_ids(&ids).reshape(&out_shape)
}
fn parameters(&self) -> Vec<Tensor> {
vec![self.weight.clone()]
}
fn named_parameters(&self) -> Vec<(String, Tensor)> {
vec![("weight".to_string(), self.weight.clone())]
}
}
impl std::fmt::Debug for Embedding {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Embedding")
.field("vocab_size", &self.vocab_size)
.field("embedding_dim", &self.embedding_dim)
.finish()
}
}