Untitled conversation
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
use candle_core::{DType, Device, Result, Tensor, D};
use candle_nn::{loss, ops, Activation, Embedding, Linear, Module, Optimizer, VarBuilder, VarMap};
const VOCAB_SIZE: u8 = 12;
const PAD: u32 = 0;
const UNK: u32 = 1;
const VOCAB_START: u32 = 2;
const ASCII_MIN: u8 = 32;
const ASCII_MAX: u8 = 126;
const EMB_DIM: usize = 1;
const HIDDEN_DIM: usize = 1;
const BATCH_SIZE: usize = 64;
const MAX_SEQ_LEN: usize = 2048;
const EPOCHS: usize = 10;
const LR: f64 = 5e-5; // Lower LR for stability with 7 layers
fn tokenize(input: char) -> u32 {
assert!(input.is_ascii());
match input {
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 4,
'e' => 5,
'f' => 6,
'g' => 7,
'h' => 8,
'j' => 9,
'k' => 10,
_ => 11,
}
}
fn split<T: Clone>(dataset: Vec<T>) -> (Vec<T>, Vec<T>) {
let x = (dataset.len() as f32 * 0.7).round() as usize;
let train = dataset[..x].into();
let test = dataset[x + 1..].into();
(train, test)
}
fn dataset() -> Vec<(char, char)> {
vec![
('a', 'b'), // 1
('b', 'c'), // 2
('c', 'd'), // 3
('d', 'e'), // 4
('e', 'f'), // 5
('f', 'g'), // 6
('g', 'h'), // 7
('h', 'i'), // 8
('i', 'j'), // 9
('j', 'k'), // 10
]
}
struct TextSet {
train_x: Tensor,
train_y: Tensor,
test_x: Tensor,
test_y: Tensor,
}
// 7-LAYER STRONK MLP
struct TheNn {
embed: Embedding,
l1: Activation,
l2: Activation,
l3: Activation,
l4: Activation,
l5: Activation,
l6: Activation,
l7: Activation,
output: Linear,
}
impl TheNn {
fn new(vs: VarBuilder) -> Result<Self> {
let embed = Embedding::new(
vs.get((VOCAB_SIZE as usize, EMB_DIM), "embed.weight")?,
VOCAB_SIZE as _,
);
let [l1, l2, l3, l4, l5, l6, l7] = [Activation::Swiglu; 7];
let output = Linear::new(
vs.get((HIDDEN_DIM, VOCAB_SIZE as usize), "output.weight")?,
Some(vs.get(VOCAB_SIZE as usize, "output.bias")?),
);
Ok(Self {
embed,
l1,
l2,
l3,
l4,
l5,
l6,
l7,
output,
})
}
fn forward(&self, ids: &Tensor) -> Result<Tensor> {
let x = self.embed.forward(ids)?; // (b, s, emb)
let x = x.mean(D::Minus2)?; // global average: (b, emb)
let x = self.l1.forward(&x)?;
let x = self.l2.forward(&x)?;
let x = self.l3.forward(&x)?;
let x = self.l4.forward(&x)?;
let x = self.l5.forward(&x)?;
let x = self.l6.forward(&x)?;
let x = self.l7.forward(&x)?;
self.output.forward(&x)
}
}
fn train_epoch(model: &TheNn, opt: &mut candle_nn::AdamW, x: &Tensor, y: &Tensor) -> Result<f32> {
let mut sum_loss = 0f32;
let logits = model.forward(x)?;
let probs = ops::log_softmax(&logits, D::Minus1)?;
let loss = loss::nll(&probs, y)?;
opt.backward_step(&loss)?;
sum_loss += loss.to_vec0::<f32>()?;
Ok(sum_loss)
}
fn accuracy(model: &TheNn, x: &Tensor, y: &Tensor) -> Result<f32> {
let logits = model.forward(x)?;
let preds = logits.argmax(D::Minus1)?;
preds
.eq(y)?
.to_dtype(DType::F32)?
.mean_all()?
.to_scalar::<f32>()
}
fn ready_dataset(dev: &Device) -> TextSet {
let (train, test) = split(dataset());
TextSet {
train_x: Tensor::new(
&*train.iter().map(|t| tokenize(t.0)).collect::<Vec<_>>(),
dev,
)
.unwrap(),
train_y: Tensor::new(
&*train.iter().map(|t| tokenize(t.1)).collect::<Vec<_>>(),
dev,
)
.unwrap(),
test_x: Tensor::new(
&*test.iter().map(|t| tokenize(t.0)).collect::<Vec<_>>(),
dev,
)
.unwrap(),
test_y: Tensor::new(
&*test.iter().map(|t| tokenize(t.1)).collect::<Vec<_>>(),
dev,
)
.unwrap(),
}
}
fn main() -> Result<()> {
let data_dir = "./data";
println!("🐒 STRONK 7-LAYER MLP INITIALIZING 🐒");
println!(
"EMB_DIM: {}, HIDDEN_DIM: {}, LAYERS: 7",
EMB_DIM, HIDDEN_DIM
);
let dev = Device::cuda_if_available(0)?;
println!(
"Using device: {}",
if dev.is_cuda() { "CUDA" } else { "CPU" }
);
let ds = ready_dataset(&dev);
let vars = VarMap::new();
let vs = VarBuilder::from_varmap(&vars, DType::F32, &dev);
let model = TheNn::new(vs.clone())?;
let mut opt = candle_nn::AdamW::new(
vars.all_vars(),
candle_nn::ParamsAdamW {
lr: LR,
weight_decay: 0.0,
..Default::default()
},
)?;
println!("🐒 TRAINING STARTING - {} EPOCHS 🐒", EPOCHS);
println!("Epoch Loss Accuracy");
println!("-------------------------");
for epoch in 1..=EPOCHS {
let train_loss = train_epoch(&model, &mut opt, &ds.train_x, &ds.train_y)?;
let acc = accuracy(&model, &ds.test_x, &ds.test_y)?;
println!("{:3} {:8.5} {:5.2}%", epoch, train_loss, 100.0 * acc);
}
println!("🐒 TRAINING COMPLETE 🐒");
// Optional: Save the model
println!("Saving model to stronk_7layer.safetensors");
vars.save("stronk_7layer.safetensors")?;
Ok(())
}
WHAT IS FUCKING WRONG?
Okay, let's break down the issues in your code and how to address them. I'll focus on the most likely causes of problems and suggest improvements.
1. Data Splitting Error:
The Problem: Your split function has an off-by-one error. You're skipping an element when creating the test set. Specifically, let test = dataset[x + 1..].into(); should likely be let test = dataset[x..].into();
Why it Matters: This leads to a smaller test set than intended and potentially skews your accuracy results. It also means you're not using all your data.
Fix:
fn split<T: Clone>(dataset: Vec<T>) -> (Vec<T>, Vec<T>) {
let x = (dataset.len() as f32 * 0.7).round() as usize;
let train = dataset[..x].to_vec(); // Use to_vec() for creating a new Vec
let test = dataset[x..].to_vec(); // Corrected split
(train, test)
}
2. Activation Layers and Hidden Dimension:
The Problem: You're using Activation::Swiglu as your activation function, but you haven't defined any linear layers to apply it to. Swiglu is typically used within a linear layer or after a linear layer to introduce non-linearity. Also, your HIDDEN_DIM is set to 1, which is extremely small and likely insufficient for any meaningful learning.
Why it Matters: Without linear layers, your model is essentially just applying the same activation function repeatedly to the input embedding, which is unlikely to learn anything useful. A hidden dimension of 1 severely limits the model's capacity.
Fix: Add linear layers between the activations and increase the hidden dimension. Here's a revised TheNn struct:
struct TheNn {
embed: Embedding,
l1: Linear,
a1: Activation,
l2: Linear,
a2: Activation,
l3: Linear,
a3: Activation,
l4: Linear,
a4: Activation,
l5: Linear,
a5: Activation,
l6: Linear,
a6: Activation,
l7: Linear,
a7: Activation,
output: Linear,
}
impl TheNn {
fn new(vs: VarBuilder) -> Result<Self> {
let embed = Embedding::new(
vs.get((VOCAB_SIZE as usize, EMB_DIM), "embed.weight")?,
VOCAB_SIZE as _,
);
let hidden_dim = 32; // Example: Increase hidden dimension
let l1 = Linear::new(vs.get((EMB_DIM, hidden_dim), "l1.weight")?, Some(vs.get(hidden_dim, "l1.bias")?));
let a1 = Activation::Swiglu;
let l2 = Linear::new(vs.get((hidden_dim, hidden_dim), "l2.weight")?, Some(vs.get(hidden_dim, "l2.bias")?));
let a2 = Activation::Swiglu;
let l3 = Linear::new(vs.get((hidden_dim, hidden_dim), "l3.weight")?, Some(vs.get(hidden_dim, "l3.bias")?));
let a3 = Activation::Swiglu;
let l4 = Linear::new(vs.get((hidden_dim, hidden_dim), "l4.weight")?, Some(vs.get(hidden_dim, "l4.bias")?));
let a4 = Activation::Swiglu;
let l5 = Linear::new(vs.get((hidden_dim, hidden_dim), "l5.weight")?, Some(vs.get(hidden_dim, "l5.bias")?));
let a5 = Activation::Swiglu;
let l6 = Linear::new(vs.get((hidden_dim, hidden_dim), "l6.weight")?, Some(vs.get(hidden_dim, "l6.bias")?));
let a6 = Activation::Swiglu;
let l7 = Linear::new(vs.get((hidden_dim, hidden_dim), "l7.weight")?, Some(vs.get(hidden_dim, "l7.bias")?));
let a7 = Activation::Swiglu;
let output = Linear::new(
vs.get((hidden_dim, VOCAB_SIZE as usize), "output.weight")?,
Some(vs.get(VOCAB_SIZE as usize, "output.bias")?),
);
Ok(Self {
embed,
l1,
a1,
l2,
a2,
l3,
a3,
l4,
a4,
l5,
a5,
l6,
a6,
l7,
a7,
output,
})
}
fn forward(&self, ids: &Tensor) -> Result<Tensor> {
let x = self.embed.forward(ids)?; // (b, s, emb)
let x = x.mean(D::Minus2)?; // global average: (b, emb)
let x = self.l1.forward(&x)?;
let x = self.a1.forward(&x)?;
let x = self.l2.forward(&x)?;
let x = self.a2.forward(&x)?;
let x = self.l3.forward(&x)?;
let x = self.a3.forward(&x)?;
let x = self.l4.forward(&x)?;
let x = self.a4.forward(&x)?;
let x = self.l5.forward(&x)?;
let x = self.a5.forward(&x)?;
let x = self.l6.forward(&x)?;
let x = self.a6.forward(&x)?;
let x = self.l7.forward(&x)?;
let x = self.a7.forward(&x)?;
self.output.forward(&x)
}
}
3. Embedding Dimension:
The Problem: EMB_DIM is set to 1. This is extremely small and will likely limit the model's ability to learn meaningful representations of the input tokens.
Why it Matters: A larger embedding dimension allows the model to capture more nuanced relationships between the tokens.
Fix: Increase EMB_DIM to a more reasonable value (e.g., 32, 64, or 128).
const EMB_DIM: usize = 32; // Example
4. Loss Calculation:
The Problem: You're calculating the loss and performing the backward pass within the train_epoch function. This is fine, but you're only processing the entire training set as a single batch. For larger datasets, this can be memory-intensive and slow.
Why it Matters: Processing the data in smaller batches (mini-batches) is generally more efficient and can lead to better generalization.
Fix: Implement mini-batching. This involves iterating over the training data in chunks of BATCH_SIZE. You'll need to slice the train_x and train_y tensors into smaller batches. This is a more involved change. Here's a basic example of how you might modify train_epoch:
fn train_epoch(model: &TheNn, opt: &mut candle_nn::AdamW, x: &Tensor, y: &Tensor) -> Result<f32> {
let mut sum_loss = 0f32;
let batch_size = BATCH_SIZE;
let num_batches = (x.dim(0)? as f64 / batch_size as f64).ceil() as usize;
for batch_idx in 0..num_batches {
let start_idx = batch_idx * batch_size;
let end_idx = std::cmp::min((batch_idx + 1) * batch_size, x.dim(0)?);
let batch_x = x.slice(D::Minus1, start_idx as u32..end_idx as u32)?;
let batch_y = y.slice(D::Minus1, start_idx as u32..end_idx as u32)?;
let logits = model.forward(&batch_x)?;
let probs = ops::log_softmax(&logits, D::Minus1)?;
let loss = loss::nll(&probs, &batch_y)?;
opt.backward_step(&loss)?;
sum_loss += loss.to_vec0::<f32>()?;
}
Ok(sum_loss / num_batches as f32) // Average loss over batches
}
5. Tokenization:
The Problem: Your tokenize function only handles a limited set of characters ('a' to 'k'). Any other character maps to the same "unknown" token (11).
Why it Matters: This severely limits the model's ability to handle diverse input.
Fix: Expand the tokenize function to handle a wider range of characters, or use a more sophisticated tokenization method (e.g., byte-pair encoding). For this simple example, you could just map each ASCII character to a unique token. You'll also need to adjust VOCAB_SIZE accordingly.
const VOCAB_SIZE: u8 = 256; // Example: All ASCII characters
fn tokenize(input: char) -> u32 {
input as u32 // Directly use the ASCII value as the token
}
6. Dataset Size:
The Problem: Your dataset is extremely small (only 10 examples).
Why it Matters: It's very difficult to train a meaningful model with so little data. The model will likely overfit to the training data and not generalize well.
Fix: Increase the size of your dataset significantly. Generate more training examples, or use a pre-existing dataset.
7. Learning Rate:
The Problem: LR is set to 5e-5. This might be too low, especially with the small dataset and potentially underpowered model.
Why it Matters: A learning rate that's too low can cause training to be very slow or even stall.
Fix: Experiment with different learning rates. Try values like 1e-4, 5e-4, or even 1e-3. You might need to adjust the learning rate as you make other changes to the model architecture and dataset.
8. Accuracy Calculation:
The Problem: You're calculating accuracy on the entire test set at once. This might be memory-intensive for larger test sets.
Why it Matters: Similar to the training loop, it's often more efficient to calculate accuracy in mini-batches.
Fix: Modify the accuracy function to process the test data in batches.
Summary of Changes and Next Steps:
split function.TheNn.EMB_DIM and HIDDEN_DIM.train_epoch.tokenize function and adjust VOCAB_SIZE.accuracy function.After making these changes, your code should be in a much better state to start training a meaningful model. Remember to monitor the training loss and accuracy to see how well the model is learning, and adjust the hyperparameters (learning rate, hidden dimension, etc.) as needed. Good luck!