Realm

Nlp Char Rnn

Runnable OA SDK tutorial.

Rust · Python

Example

1use oa::ml::{LossMetric, Module, ProgressBarCallback, SummaryCallback, Training, TrainingConfig};
2use oa::plot::{Figure, FigureConfig, LineStyle, Theme};
3use oa::{Cli, Color, LogMetrics};
4use oasdk::ml::nlp;
5
6#[derive(Default)]
7struct NlpConfig {
8 steps: u64,
9 batch: u64,
10 lr: f32,
11 plot: String,
12}
13
14fn main() -> oa::Result<()> {
15 let mut cli = Cli::new("tu_nlp_char_rnn", "OA Tutorial — Char RNN");
16 cli.add_option(
17 "--steps",
18 |c: &mut NlpConfig| &mut c.steps,
19 "training steps",
20 );
21 cli.add_option("--batch", |c: &mut NlpConfig| &mut c.batch, "batch size");
22 cli.add_option("--lr", |c: &mut NlpConfig| &mut c.lr, "learning rate");
23 cli.add_option(
24 "--plot",
25 |c: &mut NlpConfig| &mut c.plot,
26 "render the loss curve to an image file",
27 );
28 if !cli.parse() {
29 return Ok(());
30 }
31 let steps = if cli.config().steps > 0 {
32 cli.config().steps as usize
33 } else {
34 nlp::TRAINING_STEPS
35 };
36 let batch = if cli.config().batch > 0 {
37 cli.config().batch as usize
38 } else {
39 nlp::BATCH_SIZE
40 };
41 let lr = if cli.config().lr > 0.0 {
42 cli.config().lr
43 } else {
44 0.01
45 };
46
47 let runtime = oa::Runtime::new()?;
48 oa::Runtime::set_default(runtime.clone());
49 let model = nlp::CharRnn::new()?;
50 let mut optimizer = oa::ml::AdamW::new(model.all_parameters()?, lr)?;
51 let mut sampler = nlp::CharSampler::new(batch)?;
52
53 println!("\n╔══════════════════════════════════════════════════════════════════╗");
54 println!("║ OA Tutorial — Char RNN · all-position LM (autograd) ║");
55 println!("╚══════════════════════════════════════════════════════════════════╝\n");
56 println!(
57 "tokenizer: character · vocab={} (a-z + space)",
58 nlp::CHAR_VOCAB_SIZE
59 );
60 println!("Task: dense next-character prediction at every position\n");
61 println!(
62 "Model: Embedding({}) → RNN({}) → Linear({})",
63 nlp::MODEL_WIDTH,
64 nlp::HIDDEN_WIDTH,
65 nlp::CHAR_VOCAB_SIZE
66 );
67 println!(
68 "params: {} Optimizer: AdamW(lr={lr})\n",
69 model.num_parameters()?
70 );
71 println!(
72 "training: {steps} steps · batch={batch} · sequence={} character tokens",
73 nlp::CONTEXT_LENGTH
74 );
75
76 let mut loss_metric = LossMetric::default();
77 let mut progress = ProgressBarCallback::default();
78 let mut summary_callback = SummaryCallback::new();
79 let mut training = Training::new(
80 &runtime,
81 &mut optimizer,
82 TrainingConfig {
83 total_steps: steps as u64,
84 batch_size: batch as u64,
85 sequence_length: nlp::CONTEXT_LENGTH as u64,
86 sequence_unit: "token".into(),
87 timer_name: "char_rnn_training_step".into(),
88 enable_gpu_timing: true,
89 ..TrainingConfig::default()
90 },
91 )?;
92 training.add_metric(&mut loss_metric);
93 training.add_callback(&mut progress);
94 training.add_callback(&mut summary_callback);
95
96 let mut metrics = LogMetrics::new();
97 let log_dir = oa::Path::var_rel("log/nlp/char_rnn");
98 if let Err(e) = metrics.open(&log_dir) {
99 eprintln!("[OA] metrics unavailable: {e}");
100 }
101
102 let mut initial_loss = 0.0_f32;
103 let mut loss_curve = Vec::new();
104 let mut last_input = Vec::new();
105 let mut last_target = Vec::new();
106 for _ in 0..steps {
107 assert!(training.step(
108 || {
109 let (input_values, target_values) = sampler.next_values()?;
110 last_input.clone_from(&input_values);
111 last_target.clone_from(&target_values);
112 Ok((
113 oa::Matrix::new_from_slice([batch, nlp::CONTEXT_LENGTH], &input_values)?,
114 oa::Matrix::new_from_slice([batch * nlp::CONTEXT_LENGTH], &target_values)?,
115 ))
116 },
117 |(input, target)| {
118 let tape = oa::ml::GradientTape::new();
119 let logits = model.forward(&input)?;
120 let loss = oa::ml::loss::cross_entropy(&logits, &target)?;
121 tape.backward(&loss)?;
122 Ok(loss)
123 },
124 )?);
125 let snap = training.snapshot();
126 if snap.step_count() == 1 {
127 initial_loss = snap.last_loss().unwrap_or_default();
128 }
129 if let Some(loss) = snap.last_loss() {
130 loss_curve.push(loss);
131 metrics.log_scalar("loss", snap.step_count() as i64, loss as f64);
132 }
133 }
134 let program_diagnostics = training
135 .training_program()
136 .map(|program| program.diagnostics());
137 let training_result = training.finish()?;
138 let final_loss = training_result.last_loss().unwrap_or_default();
139
140 let input = oa::Matrix::new_from_slice([batch, nlp::CONTEXT_LENGTH], &last_input)?;
141 let target = oa::Matrix::new_from_slice([batch * nlp::CONTEXT_LENGTH], &last_target)?;
142 let accuracy = nlp::accuracy(&model.forward(&input)?, &target)?;
143 let generated = nlp::generate_greedy(
144 &runtime,
145 &model,
146 nlp::GENERATION_PROMPT,
147 nlp::GENERATION_LENGTH,
148 )?;
149
150 println!("\nEvaluation:");
151 println!(
152 " Random-loss baseline ln({}) = {:.4}",
153 nlp::CHAR_VOCAB_SIZE,
154 (nlp::CHAR_VOCAB_SIZE as f64).ln()
155 );
156 println!(
157 " character-token accuracy: {:.1}% (compare within Char only)",
158 accuracy * 100.0
159 );
160 println!(
161 "\nGeneration:\n prompt: {:?}\n generated: {:?}",
162 nlp::GENERATION_PROMPT,
163 generated
164 );
165 if let Some(diagnostics) = program_diagnostics {
166 println!(
167 "program: {} nodes · {} recording · {} cache hits · {} uploads",
168 diagnostics.node_count(),
169 diagnostics.command_recording_count(),
170 diagnostics.command_cache_hit_count(),
171 diagnostics.input_upload_count(),
172 );
173 }
174
175 let plot_path = cli.config().plot.as_str();
176 if !plot_path.is_empty() {
177 write_loss_curve(&loss_curve, plot_path)?;
178 println!("plot: {plot_path}");
179 }
180
181 if steps == nlp::TRAINING_STEPS && batch == nlp::BATCH_SIZE && lr == 0.01 {
182 assert!(initial_loss > 3.0);
183 assert!(final_loss < 0.25);
184 assert!(accuracy > 0.9);
185 assert_eq!(generated, nlp::CHAR_RNN_REFERENCE_GENERATION);
186 }
187
188 let checkpoint = oa::Path::temp().join("oars_char_rnn.oam");
189 oa::ml::save_checkpoint(&checkpoint, &model, &optimizer)?;
190 let reloaded = nlp::CharRnn::new()?;
191 let mut reloaded_optimizer = oa::ml::AdamW::new(reloaded.all_parameters()?, lr)?;
192 oa::ml::load_checkpoint(&checkpoint, &reloaded, &mut reloaded_optimizer)?;
193 assert_eq!(reloaded_optimizer.step_count(), optimizer.step_count());
194 assert_eq!(
195 nlp::accuracy(&reloaded.forward(&input)?, &target)?,
196 accuracy
197 );
198 assert_eq!(
199 nlp::generate_greedy(
200 &runtime,
201 &reloaded,
202 nlp::GENERATION_PROMPT,
203 nlp::GENERATION_LENGTH
204 )?,
205 generated
206 );
207 oa::Filesystem::remove_file(&checkpoint).expect("remove completed RNN checkpoint");
208 if oa::EnvFlag::is_set("OA_JIT_TRACE") {
209 println!("fusion census: {}", runtime.fusion_stats());
210 }
211 Ok(())
212}
213
214/// Render the recorded loss curve through `oa::plot` — the same headless GPU
215/// composition `tu_viewer_video` uses for its poster asset.
216fn write_loss_curve(loss_curve: &[f32], path: &str) -> oa::Result<()> {
217 let mut fig = Figure::new(FigureConfig {
218 title: "Char RNN training".to_owned(),
219 width: 960,
220 height: 540,
221 theme: Theme::Dark,
222 ..Default::default()
223 });
224 fig.title("Char RNN — dense next-character LM");
225 let steps: Vec<f32> = (1..=loss_curve.len()).map(|s| s as f32).collect();
226 let ax = fig.ax(0, 0);
227 ax.title("training loss");
228 ax.x_label("optimizer step");
229 ax.y_label("cross entropy");
230 ax.grid(true);
231 ax.legend(true);
232 let baseline = (nlp::CHAR_VOCAB_SIZE as f32).ln();
233 let peak_loss = loss_curve.iter().copied().fold(baseline, f32::max);
234 ax.limits(0.0, loss_curve.len() as f32 + 1.0, 0.0, peak_loss + 0.3);
235 ax.plot_xy(
236 &steps,
237 loss_curve,
238 LineStyle {
239 color: Color::new(0.24, 0.65, 1.0, 1.0),
240 label: "train".to_owned(),
241 width: 1.6,
242 antialias_samples: 4,
243 ..Default::default()
244 },
245 );
246 ax.plot_xy(
247 &[
248 *steps.first().unwrap_or(&0.0),
249 *steps.last().unwrap_or(&1.0),
250 ],
251 &[baseline, baseline],
252 LineStyle {
253 color: Color::new(0.565, 0.565, 0.565, 1.0),
254 label: format!("ln({}) baseline", nlp::CHAR_VOCAB_SIZE),
255 width: 1.35,
256 antialias_samples: 4,
257 ..Default::default()
258 },
259 );
260 fig.save_to(path)
261}
262

Run Rust tutorials from the OA SDK checkout with cargo run --release --example <name>. Run Python with the environment containing the OA native extension. Consult each program's arguments and capability checks before running it.