Prediction

Struct Prediction 

Source
pub struct Prediction {
    pub data: HashMap<String, Value>,
    pub lm_usage: LmUsage,
}

Fields§

§data: HashMap<String, Value>§lm_usage: LmUsage

Implementations§

Source§

impl Prediction

Source

pub fn new(data: HashMap<String, Value>, lm_usage: LmUsage) -> Self

Source

pub fn get(&self, key: &str, default: Option<&str>) -> Value

Examples found in repository?
examples/08-optimize-mipro.rs (line 173)
85async fn main() -> Result<()> {
86    println!("=== MIPROv2 Optimizer Example ===\n");
87
88    // Configure the LM
89    configure(
90        LM::builder()
91            .api_key(SecretString::from(std::env::var("OPENAI_API_KEY")?))
92            .build(),
93        ChatAdapter {},
94    );
95
96    // Load training data from HuggingFace
97    println!("Loading training data from HuggingFace...");
98    let train_examples = DataLoader::load_hf(
99        "hotpotqa/hotpot_qa",
100        vec!["question".to_string()],
101        vec!["answer".to_string()],
102        "fullwiki",
103        "validation",
104        true,
105    )?;
106
107    // Use a small subset for faster optimization
108    let train_subset = train_examples[..15].to_vec();
109    println!("Using {} training examples\n", train_subset.len());
110
111    // Create the module
112    let mut qa_module = SimpleQA::builder().build();
113
114    // Show initial instruction
115    println!("Initial instruction:");
116    println!(
117        "  \"{}\"\n",
118        qa_module.answerer.get_signature().instruction()
119    );
120
121    // Test baseline performance
122    println!("Evaluating baseline performance...");
123    let baseline_score = qa_module.evaluate(train_subset[..5].to_vec()).await;
124    println!("Baseline score: {:.3}\n", baseline_score);
125
126    // Create MIPROv2 optimizer
127    let optimizer = MIPROv2::builder()
128        .num_candidates(8) // Generate 8 candidate prompts
129        .num_trials(15) // Run 15 evaluation trials
130        .minibatch_size(10) // Evaluate on 10 examples per candidate
131        .temperature(1.0) // Temperature for prompt generation
132        .track_stats(true) // Display detailed statistics
133        .build();
134
135    // Optimize the module
136    println!("Starting MIPROv2 optimization...");
137    println!("This will:");
138    println!("  1. Generate execution traces");
139    println!("  2. Create a program description using LLM");
140    println!("  3. Generate {} candidate prompts with best practices", 8);
141    println!("  4. Evaluate each candidate");
142    println!("  5. Select and apply the best prompt\n");
143
144    optimizer.compile(&mut qa_module, train_subset.clone()).await?;
145
146    // Show optimized instruction
147    println!("\nOptimized instruction:");
148    println!(
149        "  \"{}\"\n",
150        qa_module.answerer.get_signature().instruction()
151    );
152
153    // Test optimized performance
154    println!("Evaluating optimized performance...");
155    let optimized_score = qa_module.evaluate(train_subset[..5].to_vec()).await;
156    println!("Optimized score: {:.3}", optimized_score);
157
158    // Show improvement
159    let improvement = ((optimized_score - baseline_score) / baseline_score) * 100.0;
160    println!(
161        "\n✓ Improvement: {:.1}% ({:.3} -> {:.3})",
162        improvement, baseline_score, optimized_score
163    );
164
165    // Test on a new example
166    println!("\n--- Testing on a new example ---");
167    let test_example = example! {
168        "question": "input" => "What is the capital of France?",
169    };
170
171    let result = qa_module.forward(test_example).await?;
172    println!("Question: What is the capital of France?");
173    println!("Answer: {}", result.get("answer", None));
174
175    println!("\n=== Example Complete ===");
176    Ok(())
177}
Source

pub fn keys(&self) -> Vec<String>

Source

pub fn values(&self) -> Vec<Value>

Source

pub fn set_lm_usage(&mut self, lm_usage: LmUsage) -> Self

Examples found in repository?
examples/01-simple.rs (line 66)
49    async fn forward(&self, inputs: Example) -> Result<Prediction> {
50        let answerer_prediction = self.answerer.forward(inputs.clone()).await?;
51
52        let question = inputs.data.get("question").unwrap().clone();
53        let answer = answerer_prediction.data.get("answer").unwrap().clone();
54
55        let inputs = example! {
56            "question": "input" => question.clone(),
57            "answer": "output" => answer.clone()
58        };
59
60        let rating_prediction = self.rater.forward(inputs).await?;
61        Ok(prediction! {
62            "answer"=> answer,
63            "question"=> question,
64            "rating"=> rating_prediction.data.get("rating").unwrap().clone(),
65        }
66        .set_lm_usage(rating_prediction.lm_usage))
67    }
More examples
Hide additional examples
examples/02-module-iteration-and-updation.rs (line 86)
66    async fn forward(&self, inputs: Example) -> Result<Prediction> {
67        let answerer_prediction = self.answerer.forward(inputs.clone()).await?;
68
69        let question = inputs.data.get("question").unwrap().clone();
70        let answer = answerer_prediction.data.get("answer").unwrap().clone();
71
72        let inputs = Example::new(
73            hashmap! {
74                "answer".to_string() => answer.clone(),
75                "question".to_string() => question.clone()
76            },
77            vec!["answer".to_string(), "question".to_string()],
78            vec![],
79        );
80        let rating_prediction = self.rater.forward(inputs).await?;
81        Ok(prediction! {
82            "answer"=> answer,
83            "question"=> question,
84            "rating"=> rating_prediction.data.get("rating").unwrap().clone(),
85        }
86        .set_lm_usage(rating_prediction.lm_usage))
87    }
examples/06-oai-compatible-models-batch.rs (line 73)
50    async fn forward(&self, inputs: Example) -> Result<Prediction> {
51        let answerer_prediction = self.answerer.forward(inputs.clone()).await?;
52
53        let question = inputs.data.get("question").unwrap().clone();
54        let answer = answerer_prediction.data.get("answer").unwrap().clone();
55        let answer_lm_usage = answerer_prediction.lm_usage;
56
57        let inputs = Example::new(
58            hashmap! {
59                "answer".to_string() => answer.clone(),
60                "question".to_string() => question.clone()
61            },
62            vec!["answer".to_string(), "question".to_string()],
63            vec![],
64        );
65        let rating_prediction = self.rater.forward(inputs).await?;
66        let rating_lm_usage = rating_prediction.lm_usage;
67
68        Ok(prediction! {
69            "answer"=> answer,
70            "question"=> question,
71            "rating"=> rating_prediction.data.get("rating").unwrap().clone(),
72        }
73        .set_lm_usage(answer_lm_usage + rating_lm_usage))
74    }

Trait Implementations§

Source§

impl Clone for Prediction

Source§

fn clone(&self) -> Prediction

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Prediction

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Default for Prediction

Source§

fn default() -> Prediction

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Prediction

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Index<String> for Prediction

Source§

type Output = Value

The returned type after indexing.
Source§

fn index(&self, index: String) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl Serialize for Prediction

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. 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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> ErasedDestructor for T
where T: 'static,