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.



1994
1995
1996
# File 'lib/dspy/teleprompt/gepa.rb', line 1994

def initialize(config:)
  @config = config
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



1991
1992
1993
# File 'lib/dspy/teleprompt/gepa.rb', line 1991

def config
  @config
end

Instance Method Details

#batch_crossover(population) ⇒ Object



2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
# File 'lib/dspy/teleprompt/gepa.rb', line 2024

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



2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
# File 'lib/dspy/teleprompt/gepa.rb', line 2000

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