Class: Desiru::Optimizers::MIPROv2

Inherits:
Base
  • Object
show all
Defined in:
lib/desiru/optimizers/mipro_v2.rb

Overview

MIPROv2 - Multi-objective Instruction Prompt Optimization v2 Uses Bayesian optimization to optimize prompts and demonstrations across multiple objectives

Defined Under Namespace

Classes: GaussianProcess

Instance Attribute Summary collapse

Attributes inherited from Base

#config, #metric

Instance Method Summary collapse

Methods inherited from Base

#evaluate

Constructor Details

#initialize(metric: :exact_match, objectives: nil, **config) ⇒ MIPROv2

Returns a new instance of MIPROv2.



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/desiru/optimizers/mipro_v2.rb', line 12

def initialize(metric: :exact_match, objectives: nil, **config)
  super(metric: metric, **config)
  @objectives = normalize_objectives(objectives || [metric])
  @optimization_history = []
  @pareto_frontier = []
  @gaussian_process = GaussianProcess.new
  @acquisition_function = config[:acquisition_function] || :expected_improvement
  @trace_collector = config[:trace_collector] || Core.trace_collector
  @instruction_candidates = []
  @demonstration_candidates = []
end

Instance Attribute Details

#optimization_historyObject (readonly)

Returns the value of attribute optimization_history.



10
11
12
# File 'lib/desiru/optimizers/mipro_v2.rb', line 10

def optimization_history
  @optimization_history
end

#pareto_frontierObject (readonly)

Returns the value of attribute pareto_frontier.



10
11
12
# File 'lib/desiru/optimizers/mipro_v2.rb', line 10

def pareto_frontier
  @pareto_frontier
end

#trace_collectorObject (readonly)

Returns the value of attribute trace_collector.



10
11
12
# File 'lib/desiru/optimizers/mipro_v2.rb', line 10

def trace_collector
  @trace_collector
end

Instance Method Details

#compile(program, trainset:, valset: nil) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/desiru/optimizers/mipro_v2.rb', line 24

def compile(program, trainset:, valset: nil)
  trace_optimization('Starting MIPROv2 optimization', {
                       trainset_size: trainset.size,
                       valset_size: valset&.size || 0,
                       objectives: @objectives.map(&:to_s),
                       config: config
                     })

  begin
    # Initialize optimization state
    @current_program = deep_copy_program(program)
    @trainset = trainset
    @valset = valset || trainset
    @iteration = 0

    # Clear trace collector for fresh optimization
    @trace_collector.clear if config[:clear_traces]

    # Enable tracing on all modules
    enable_program_tracing(@current_program)

    # Run Bayesian optimization loop
    while @iteration < config[:max_iterations] && !should_stop?
      @iteration += 1
      trace_optimization("Iteration #{@iteration}", { phase: 'start' })

      # Generate candidates using acquisition function
      candidates = generate_candidates

      # Evaluate candidates
      evaluated_candidates = evaluate_candidates(candidates)

      # Update Gaussian Process with results
      update_gaussian_process(evaluated_candidates)

      # Update Pareto frontier for multi-objective optimization
      update_pareto_frontier(evaluated_candidates)

      # Select best candidate
      best_candidate = select_best_candidate(evaluated_candidates)

      # Apply best candidate to program
      apply_candidate(@current_program, best_candidate) if best_candidate

      # Log iteration results - always log even if no best candidate
      if best_candidate
        log_iteration_results(best_candidate, evaluated_candidates)
      elsif evaluated_candidates.any?
        # Log with the first candidate if no best found
        log_iteration_results(evaluated_candidates.first, evaluated_candidates)
      end
    end

    # Restore trace state
    disable_program_tracing(@current_program) if config[:restore_trace_state]

    # Return optimized program
    @current_program
  rescue StandardError => e
    trace_optimization('Optimization failed', { error: e.message, backtrace: e.backtrace.first(3) })
    begin
      disable_program_tracing(@current_program) if config[:restore_trace_state]
    rescue StandardError
      nil
    end

    # Return original program on error
    program
  ensure
    # Always disable tracing at the end if enabled
    begin
      disable_program_tracing(@current_program) if config[:restore_trace_state]
    rescue StandardError
      nil
    end
  end
end

#evaluate_module_config(module_instance, instruction, demos, examples) ⇒ Object



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/desiru/optimizers/mipro_v2.rb', line 168

def evaluate_module_config(module_instance, instruction, demos, examples)
  # Simple evaluation - could be enhanced
  test_module = module_instance.with_demos(demos)

  test_module.instruction = instruction if test_module.respond_to?(:instruction=) && instruction

  # Evaluate on subset of examples
  eval_examples = examples.sample([examples.size, 5].min)
  scores = eval_examples.map do |ex|
    # Extract inputs (exclude answer/output fields)
    inputs = {}
    ex.to_h.each do |k, v|
      inputs[k] = v unless i[answer output].include?(k)
    end

    result = test_module.call(inputs)
    score_prediction(result, ex)
  rescue StandardError
    0.0
  end

  scores.empty? ? 0.0 : scores.sum.to_f / scores.size
end

#generate_demonstration_sets(_module_instance, examples) ⇒ Object



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/desiru/optimizers/mipro_v2.rb', line 146

def generate_demonstration_sets(_module_instance, examples)
  return [[]] if examples.empty?

  # Generate different demo sets
  sets = []

  # Empty set
  sets << []

  # Random subset
  [1, 2, 3].each do |count|
    break if count > examples.size

    sets << examples.sample(count)
  end

  # Diverse set
  sets << select_diverse_demonstrations(examples, [examples.size, 3].min, Random.new) if examples.size > 1

  sets
end

#generate_instruction_variants(module_instance, _examples) ⇒ Object



136
137
138
139
140
141
142
143
144
# File 'lib/desiru/optimizers/mipro_v2.rb', line 136

def generate_instruction_variants(module_instance, _examples)
  # Generate different instruction styles
  signature = module_instance.signature
  [
    generate_instruction(signature, 'concise', 0.2),
    generate_instruction(signature, 'detailed', 0.5),
    generate_instruction(signature, 'step-by-step', 0.8)
  ]
end

#optimize_module(module_instance, examples) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/desiru/optimizers/mipro_v2.rb', line 102

def optimize_module(module_instance, examples)
  trace_optimization('Optimizing module with MIPROv2', {
                       module: module_instance.class.name,
                       examples_count: examples.size
                     })

  # Generate instruction variants
  instruction_variants = generate_instruction_variants(module_instance, examples)

  # Generate demonstration sets
  demo_sets = generate_demonstration_sets(module_instance, examples)

  # Evaluate all combinations
  best_config = nil
  best_score = -Float::INFINITY

  instruction_variants.each do |instruction|
    demo_sets.each do |demos|
      score = evaluate_module_config(module_instance, instruction, demos, examples)

      if score > best_score
        best_score = score
        best_config = { instruction: instruction, demos: demos }
      end
    end
  end

  # Create optimized module
  optimized = module_instance.with_demos(best_config[:demos])
  optimized.instruction = best_config[:instruction] if optimized.respond_to?(:instruction=)

  optimized
end