Skip to main content

Script

Struct Script 

Source
pub struct Script { /* private fields */ }
Expand description

Script - executable module with compilation and execution capabilities

Implementations§

Source§

impl Script

Source

pub fn new(module: Module) -> Script

Create a new script from a module

Source

pub fn module(&self) -> &Module

Get the module

Source

pub fn name(&self) -> &str

Get the module name

Source

pub fn set_compiler(&mut self, compiler: Compiler)

Set compiler type

Source

pub fn set_device(&mut self, device: Device)

Set target device

Source

pub fn compiler(&self) -> Compiler

Get current compiler type

Source

pub fn device(&self) -> Device

Get current device

Source

pub fn set_input(&mut self, name: &str, tensor: Tensor)

Add an input tensor

Examples found in repository?
examples/simple-linear-train-script.rs (line 67)
4fn main() -> Result<(), Box<dyn std::error::Error>> {
5    let input_data: Vec<Vec<f32>> = (0..10000)
6        .map(|i| {
7            vec![
8                (i % 100) as f32 / 100.0,
9                ((i % 100) + 1) as f32 / 100.0,
10                ((i % 100) + 2) as f32 / 100.0,
11            ]
12        })
13        .collect();
14    let target_data: Vec<Vec<f32>> = (0..10000).map(|i| vec![((i % 100) * 10) as f32 / 1000.0]).collect();
15
16    let input_tensor = Tensor::new(input_data)?;
17    let target_tensor = Tensor::new(target_data)?;
18
19    // Build script using new API
20    let builder = Builder::new("linear_training".to_string());
21    builder.start()?;
22
23    let mut linear = Linear::new(3, 1, true, DType::F32)?;
24    let mse_loss = MSELoss::new();
25    let mut optimizer = SGD::new(0.01);
26
27    let input = Tensor::input("input", [10000, 3])?;
28    input.requires_grad()?;
29    let target = Tensor::input("target", [10000, 1])?;
30
31    let epochs = 1000;
32    let mut final_loss = Tensor::scalar(0.0)?;
33
34    for _ in 0..epochs {
35        let pred = linear.forward(&input)?;
36        let loss = mse_loss.forward((&pred, &target))?;
37
38        loss.backward()?;
39
40        optimizer.step(&mut linear.parameters())?;
41        optimizer.zero_grad(&mut linear.parameters())?;
42
43        final_loss = loss;
44    }
45
46    let params = linear.parameters();
47    builder.add_output("loss", final_loss)?;
48    builder.add_output("weight", params[0].clone())?;
49    builder.add_output("bias", params[1].clone())?;
50
51    builder.end()?;
52
53    // Build script
54    let mut script = builder.build()?;
55
56    // Set device
57    #[cfg(feature = "cuda")]
58    script.set_device(Device::CUDA(0));
59    #[cfg(feature = "metal")]
60    script.set_device(Device::Metal);
61
62    // Set compiler type
63    #[cfg(feature = "xla")]
64    script.set_compiler(Compiler::XLA);
65
66    // Set runtime inputs
67    script.set_input("input", input_tensor);
68    script.set_input("target", target_tensor);
69
70    println!("Compiling script...");
71    let compile_start = Instant::now();
72    script.compile()?;
73    let compile_elapsed = compile_start.elapsed();
74    println!("Compilation time: {:?}", compile_elapsed);
75
76    println!("Running script...");
77    let run_start = Instant::now();
78    let output = script.run()?;
79    let run_elapsed = run_start.elapsed();
80
81    println!("Loss: {}", output["loss"]);
82    println!("Weight: {}", output["weight"]);
83    println!("Bias: {}", output["bias"]);
84    println!("Execution time: {:?}", run_elapsed);
85    println!("Total time: {:?}", compile_elapsed + run_elapsed);
86
87    Ok(())
88}
Source

pub fn with_input(self, name: &str, tensor: Tensor) -> Script

Add an input tensor (builder pattern)

Source

pub fn clear_inputs(&mut self)

Clear all runtime inputs

Source

pub fn inputs(&self) -> &HashMap<String, Tensor>

Get current runtime inputs

Source

pub fn compile(&mut self) -> Result<(), HoduError>

Compile the module

Examples found in repository?
examples/simple-linear-train-script.rs (line 72)
4fn main() -> Result<(), Box<dyn std::error::Error>> {
5    let input_data: Vec<Vec<f32>> = (0..10000)
6        .map(|i| {
7            vec![
8                (i % 100) as f32 / 100.0,
9                ((i % 100) + 1) as f32 / 100.0,
10                ((i % 100) + 2) as f32 / 100.0,
11            ]
12        })
13        .collect();
14    let target_data: Vec<Vec<f32>> = (0..10000).map(|i| vec![((i % 100) * 10) as f32 / 1000.0]).collect();
15
16    let input_tensor = Tensor::new(input_data)?;
17    let target_tensor = Tensor::new(target_data)?;
18
19    // Build script using new API
20    let builder = Builder::new("linear_training".to_string());
21    builder.start()?;
22
23    let mut linear = Linear::new(3, 1, true, DType::F32)?;
24    let mse_loss = MSELoss::new();
25    let mut optimizer = SGD::new(0.01);
26
27    let input = Tensor::input("input", [10000, 3])?;
28    input.requires_grad()?;
29    let target = Tensor::input("target", [10000, 1])?;
30
31    let epochs = 1000;
32    let mut final_loss = Tensor::scalar(0.0)?;
33
34    for _ in 0..epochs {
35        let pred = linear.forward(&input)?;
36        let loss = mse_loss.forward((&pred, &target))?;
37
38        loss.backward()?;
39
40        optimizer.step(&mut linear.parameters())?;
41        optimizer.zero_grad(&mut linear.parameters())?;
42
43        final_loss = loss;
44    }
45
46    let params = linear.parameters();
47    builder.add_output("loss", final_loss)?;
48    builder.add_output("weight", params[0].clone())?;
49    builder.add_output("bias", params[1].clone())?;
50
51    builder.end()?;
52
53    // Build script
54    let mut script = builder.build()?;
55
56    // Set device
57    #[cfg(feature = "cuda")]
58    script.set_device(Device::CUDA(0));
59    #[cfg(feature = "metal")]
60    script.set_device(Device::Metal);
61
62    // Set compiler type
63    #[cfg(feature = "xla")]
64    script.set_compiler(Compiler::XLA);
65
66    // Set runtime inputs
67    script.set_input("input", input_tensor);
68    script.set_input("target", target_tensor);
69
70    println!("Compiling script...");
71    let compile_start = Instant::now();
72    script.compile()?;
73    let compile_elapsed = compile_start.elapsed();
74    println!("Compilation time: {:?}", compile_elapsed);
75
76    println!("Running script...");
77    let run_start = Instant::now();
78    let output = script.run()?;
79    let run_elapsed = run_start.elapsed();
80
81    println!("Loss: {}", output["loss"]);
82    println!("Weight: {}", output["weight"]);
83    println!("Bias: {}", output["bias"]);
84    println!("Execution time: {:?}", run_elapsed);
85    println!("Total time: {:?}", compile_elapsed + run_elapsed);
86
87    Ok(())
88}
Source

pub fn is_compiled(&self) -> bool

Check if the script is compiled

Source

pub fn run(&mut self) -> Result<HashMap<String, Tensor>, HoduError>

Execute the compiled script

Examples found in repository?
examples/simple-linear-train-script.rs (line 78)
4fn main() -> Result<(), Box<dyn std::error::Error>> {
5    let input_data: Vec<Vec<f32>> = (0..10000)
6        .map(|i| {
7            vec![
8                (i % 100) as f32 / 100.0,
9                ((i % 100) + 1) as f32 / 100.0,
10                ((i % 100) + 2) as f32 / 100.0,
11            ]
12        })
13        .collect();
14    let target_data: Vec<Vec<f32>> = (0..10000).map(|i| vec![((i % 100) * 10) as f32 / 1000.0]).collect();
15
16    let input_tensor = Tensor::new(input_data)?;
17    let target_tensor = Tensor::new(target_data)?;
18
19    // Build script using new API
20    let builder = Builder::new("linear_training".to_string());
21    builder.start()?;
22
23    let mut linear = Linear::new(3, 1, true, DType::F32)?;
24    let mse_loss = MSELoss::new();
25    let mut optimizer = SGD::new(0.01);
26
27    let input = Tensor::input("input", [10000, 3])?;
28    input.requires_grad()?;
29    let target = Tensor::input("target", [10000, 1])?;
30
31    let epochs = 1000;
32    let mut final_loss = Tensor::scalar(0.0)?;
33
34    for _ in 0..epochs {
35        let pred = linear.forward(&input)?;
36        let loss = mse_loss.forward((&pred, &target))?;
37
38        loss.backward()?;
39
40        optimizer.step(&mut linear.parameters())?;
41        optimizer.zero_grad(&mut linear.parameters())?;
42
43        final_loss = loss;
44    }
45
46    let params = linear.parameters();
47    builder.add_output("loss", final_loss)?;
48    builder.add_output("weight", params[0].clone())?;
49    builder.add_output("bias", params[1].clone())?;
50
51    builder.end()?;
52
53    // Build script
54    let mut script = builder.build()?;
55
56    // Set device
57    #[cfg(feature = "cuda")]
58    script.set_device(Device::CUDA(0));
59    #[cfg(feature = "metal")]
60    script.set_device(Device::Metal);
61
62    // Set compiler type
63    #[cfg(feature = "xla")]
64    script.set_compiler(Compiler::XLA);
65
66    // Set runtime inputs
67    script.set_input("input", input_tensor);
68    script.set_input("target", target_tensor);
69
70    println!("Compiling script...");
71    let compile_start = Instant::now();
72    script.compile()?;
73    let compile_elapsed = compile_start.elapsed();
74    println!("Compilation time: {:?}", compile_elapsed);
75
76    println!("Running script...");
77    let run_start = Instant::now();
78    let output = script.run()?;
79    let run_elapsed = run_start.elapsed();
80
81    println!("Loss: {}", output["loss"]);
82    println!("Weight: {}", output["weight"]);
83    println!("Bias: {}", output["bias"]);
84    println!("Execution time: {:?}", run_elapsed);
85    println!("Total time: {:?}", compile_elapsed + run_elapsed);
86
87    Ok(())
88}
Source

pub fn to_bytes(&self) -> Result<Vec<u8>, HoduError>

Serialize the module to bytes (no_std compatible)

Source

pub fn from_bytes(bytes: &[u8]) -> Result<Script, HoduError>

Deserialize a script from bytes (no_std compatible)

Source

pub fn save<P>(&self, path: P) -> Result<(), HoduError>
where P: AsRef<Path>,

Save the module to file (requires std)

Source

pub fn load<P>(path: P) -> Result<Script, HoduError>
where P: AsRef<Path>,

Load a script from file (requires std)

Trait Implementations§

Source§

impl Debug for Script

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V