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?
It seems like you're asking for help debugging your Rust code, specifically why it might not be training as expected or if there are any obvious errors. Let's break down the code and see if we can spot any potential issues.
Here's a breakdown of potential problems and things to check:
1. Overly Complex Model for a Simple Task:
EMB_DIM and HIDDEN_DIM are both set to 1. This severely limits the model's capacity to learn complex relationships. While the task is simple, such a small dimension might be too restrictive.2. Dataset and Splitting:
split function dataset[x + 1..] skips an element in the dataset. It should likely be dataset[x..] for the test set to start from the correct index. However, with only 10 examples, splitting might be detrimental. You might be better off training on all 10 examples for such a simple task, or at least adjust the split to be more reasonable.3. Global Average Pooling:
x.mean(D::Minus2)?: You are performing global average pooling after the embedding layer. This is usually used for sequence data to aggregate information across the sequence length. However, in your current setup, you are feeding in single characters as input. Global average pooling in this context might not be meaningful or helpful. It's averaging across the embedding dimension, but since EMB_DIM is 1, it's essentially doing nothing significant. If you intend to process sequences, the input and data preparation need to be adjusted accordingly. If you are processing single characters, this pooling is likely unnecessary.4. Learning Rate:
LR: 5e-5: This is a very low learning rate, especially for a small model and dataset. While low learning rates can sometimes improve stability, they can also make training very slow or get stuck in local minima. For this simple problem, you might want to try a slightly higher learning rate initially (e.g., or ).1e-31e-45. Activation Functions:
Let's try to simplify and debug:
Here's a modified version of your code with some suggestions to make it more likely to train and easier to debug:
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 = 8; // Increased embedding dimension
const HIDDEN_DIM: usize = 8; // Increased hidden dimension
const BATCH_SIZE: usize = 64;
const MAX_SEQ_LEN: usize = 2048;
const EPOCHS: usize = 200; // Increased epochs to see if it learns
const LR: f64 = 1e-3; // Increased learning rate
const LAYERS: usize = 2; // Reduced 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,
'i' => 9,
'j' => 10,
_ => 11, // UNK
}
}
fn split<T: Clone>(dataset: Vec<T>) -> (Vec<T>, Vec<T>) {
let x = (dataset.len() as f32 * 0.8).round() as usize; // 80/20 split
let train = dataset[..x].to_vec(); // To vec to create new Vec
let test = dataset[x..].to_vec(); // Corrected split
(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
('g', 'h'), // 7 - Duplicated to make dataset slightly larger
('h', 'i'), // 8
('i', 'j'), // 9
('j', 'k'), // 10
('a', 'c'), // Extra example
('b', 'd'), // Extra example
]
}
struct TextSet {
train_x: Tensor,
train_y: Tensor,
test_x: Tensor,
test_y: Tensor,
}
// Simplified MLP
struct TheNn {
embed: Embedding,
layers: Vec<Linear>, // Using Vec for layers
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 mut layers = Vec::new();
for i in 0..LAYERS {
let layer = Linear::new(
vs.get((HIDDEN_DIM, HIDDEN_DIM), format!("layer{}.weight", i).as_str())?,
Some(vs.get(HIDDEN_DIM, format!("layer{}.bias", i).as_str())?),
);
layers.push(layer);
}
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,
layers,
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) - Still keeping it for now, but consider removing
let mut current_x = x;
for layer in &self.layers {
current_x = layer.forward(¤t_x)?;
current_x = Activation::Swiglu.forward(¤t_x)?; // Activation after each layer
}
self.output.forward(¤t_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 MLP INITIALIZING 🐒"); // Removed 7-layer from name
println!(
"EMB_DIM: {}, HIDDEN_DIM: {}, LAYERS: {}",
EMB_DIM, HIDDEN_DIM, LAYERS
);
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_mlp.safetensors"); // Changed filename
vars.save("stronk_mlp.safetensors")?;
Ok(())
}
Key Changes and Suggestions:
LAYERS constant is now 2. You can experiment with 1 or 3 as well.EMB_DIM and HIDDEN_DIM are increased to 8. This gives the model a bit more capacity.LR is increased to 1e-3.EPOCHS is increased to 200 to give the model more time to learn.split function is corrected to include the last element of the training set in the test set. Also, using to_vec() to create new Vecs in split.Vec<Linear> to represent the layers makes the code cleaner and easier to adjust the number of layers.Run this modified code and see if the loss decreases and accuracy increases.
Further Debugging Steps if it's still not working:
x.mean(D::Minus2)? from the forward function.Embedding layer followed directly by the output Linear layer (no hidden layers at all) to see if the embedding and output layers themselves can learn the mapping.println! statements inside forward to print the shape and values of tensors at different stages (e.g., after embedding, after each layer) to inspect the data flow and see if anything looks wrong (NaNs, zeros, unexpected shapes).train_x, train_y, test_x, test_y tensors contain the correct token IDs after ready_dataset.tokenize to just return the ASCII value directly (if you are sure your vocabulary covers the input characters) or a very basic mapping.By systematically simplifying and checking each part, you should be able to pinpoint what's preventing your model from learning. Let me know how it goes with these changes!