Optimizable

Trait Optimizable 

Source
pub trait Optimizable {
    // Required method
    fn parameters(&mut self) -> IndexMap<String, &mut dyn Optimizable>;

    // Provided methods
    fn get_signature(&self) -> &dyn MetaSignature { ... }
    fn update_signature_instruction(
        &mut self,
        instruction: String,
    ) -> Result<()> { ... }
}

Required Methods§

Source

fn parameters(&mut self) -> IndexMap<String, &mut dyn Optimizable>

Provided Methods§

Source

fn get_signature(&self) -> &dyn MetaSignature

Examples found in repository?
examples/04-optimize-hotpotqa.rs (line 80)
59async fn main() -> anyhow::Result<()> {
60    configure(
61        LM::builder()
62            .api_key(SecretString::from(std::env::var("OPENAI_API_KEY")?))
63            .build(),
64        ChatAdapter {},
65    );
66
67    let examples = DataLoader::load_hf(
68        "hotpotqa/hotpot_qa",
69        vec!["question".to_string()],
70        vec!["answer".to_string()],
71        "fullwiki",
72        "validation",
73        true,
74    )?[..10]
75        .to_vec();
76
77    let mut rater = QARater::builder().build();
78    let optimizer = COPRO::builder().breadth(10).depth(1).build();
79
80    println!("Rater: {:?}", rater.answerer.get_signature().instruction());
81
82    optimizer.compile(&mut rater, examples.clone()).await?;
83
84    println!("Rater: {:?}", rater.answerer.get_signature().instruction());
85
86    Ok(())
87}
More examples
Hide additional examples
examples/08-optimize-mipro.rs (line 118)
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

fn update_signature_instruction(&mut self, instruction: String) -> Result<()>

Examples found in repository?
examples/02-module-iteration-and-updation.rs (line 96)
91async fn main() {
92    // Single module test
93    let mut qa_rater = QARater::builder().build();
94    for (name, param) in qa_rater.parameters() {
95        param
96            .update_signature_instruction("Updated instruction for ".to_string() + &name)
97            .unwrap();
98    }
99    println!(
100        "single.answerer -> {}",
101        qa_rater.answerer.signature.instruction()
102    );
103    println!(
104        "single.rater    -> {}",
105        qa_rater.rater.signature.instruction()
106    );
107
108    // Nested module test
109    let mut nested = NestedModule::builder().build();
110    for (name, param) in nested.parameters() {
111        param
112            .update_signature_instruction("Deep updated: ".to_string() + &name)
113            .unwrap();
114    }
115
116    // Show nested updates (module-in-module)
117    println!(
118        "nested.qa_outer.answerer -> {}",
119        nested.qa_outer.answerer.signature.instruction()
120    );
121    println!(
122        "nested.qa_outer.rater    -> {}",
123        nested.qa_outer.rater.signature.instruction()
124    );
125    println!(
126        "nested.qa_inner.answerer -> {}",
127        nested.qa_inner.answerer.signature.instruction()
128    );
129    println!(
130        "nested.qa_inner.rater    -> {}",
131        nested.qa_inner.rater.signature.instruction()
132    );
133    println!(
134        "nested.extra    -> {}",
135        nested.extra.signature.instruction()
136    );
137}

Implementors§