Class: DSPy::Teleprompt::GEPA::CrossoverEngine

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/dspy/teleprompt/gepa.rb

Overview

CrossoverEngine: Handles genetic recombination of prompts for diversity

Defined Under Namespace

Classes: InstructionComponents

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config:) ⇒ CrossoverEngine

Returns a new instance of CrossoverEngine.



2254
2255
2256
# File 'lib/dspy/teleprompt/gepa.rb', line 2254

def initialize(config:)
  @config = config
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



2251
2252
2253
# File 'lib/dspy/teleprompt/gepa.rb', line 2251

def config
  @config
end

Instance Method Details

#batch_crossover(population) ⇒ Object



2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
# File 'lib/dspy/teleprompt/gepa.rb', line 2284

def batch_crossover(population)
  return [] if population.empty?
  return [population.first] if population.size == 1
  
  offspring = []
  
  # Pair up population for crossover
  population.each_slice(2) do |pair|
    if pair.size == 2
      crossed = crossover_programs(pair[0], pair[1])
      offspring.concat(crossed)
    else
      offspring << pair[0] # Unpaired individual passes through
    end
  end
  
  offspring
end

#crossover_programs(parent_a, parent_b) ⇒ Object



2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
# File 'lib/dspy/teleprompt/gepa.rb', line 2260

def crossover_programs(parent_a, parent_b)
  return [parent_a, parent_b] if rand > @config.crossover_rate

  begin
    instruction_a = extract_instruction(parent_a)
    instruction_b = extract_instruction(parent_b)
    
    crossover_type = select_crossover_type(instruction_a, instruction_b)
    offspring_instructions = apply_crossover(instruction_a, instruction_b, crossover_type)
    
    offspring = [
      create_crossover_program(parent_a, offspring_instructions[0]),
      create_crossover_program(parent_b, offspring_instructions[1])
    ]
    
    offspring
  rescue => e
    # Return original parents on crossover failure
    [parent_a, parent_b]
  end
end