ruby-on-dspy 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +112 -0
- data/LICENSE +21 -0
- data/README.md +442 -0
- data/exe/ruby-on-dspy +7 -0
- data/lib/dspy_rb/cli.rb +83 -0
- data/lib/dspy_rb/clients/dummy_lm.rb +81 -0
- data/lib/dspy_rb/clients/lm.rb +44 -0
- data/lib/dspy_rb/datasets/data_loader.rb +74 -0
- data/lib/dspy_rb/datasets/dataset.rb +37 -0
- data/lib/dspy_rb/datasets/python_random.rb +38 -0
- data/lib/dspy_rb/errors.rb +135 -0
- data/lib/dspy_rb/evaluate/evaluate.rb +53 -0
- data/lib/dspy_rb/evaluate/metric.rb +61 -0
- data/lib/dspy_rb/execution/around.rb +63 -0
- data/lib/dspy_rb/execution/collector.rb +61 -0
- data/lib/dspy_rb/execution/context.rb +160 -0
- data/lib/dspy_rb/execution/evaluation.rb +90 -0
- data/lib/dspy_rb/execution/optimization.rb +71 -0
- data/lib/dspy_rb/execution/program.rb +126 -0
- data/lib/dspy_rb/execution/rows.rb +41 -0
- data/lib/dspy_rb/execution/scorer.rb +68 -0
- data/lib/dspy_rb/execution/step.rb +116 -0
- data/lib/dspy_rb/execution/toolbox.rb +28 -0
- data/lib/dspy_rb/predict/chain_of_thought.rb +22 -0
- data/lib/dspy_rb/predict/predict.rb +101 -0
- data/lib/dspy_rb/predict/react.rb +80 -0
- data/lib/dspy_rb/primitives/module.rb +105 -0
- data/lib/dspy_rb/primitives/parts.rb +121 -0
- data/lib/dspy_rb/runtime/channel/callback.rb +105 -0
- data/lib/dspy_rb/runtime/channel/ending.rb +35 -0
- data/lib/dspy_rb/runtime/channel/exchange.rb +176 -0
- data/lib/dspy_rb/runtime/channel/gate.rb +74 -0
- data/lib/dspy_rb/runtime/channel/listener.rb +125 -0
- data/lib/dspy_rb/runtime/channel/meter.rb +46 -0
- data/lib/dspy_rb/runtime/channel/reporter.rb +68 -0
- data/lib/dspy_rb/runtime/channel/settler.rb +69 -0
- data/lib/dspy_rb/runtime/channel/traffic.rb +121 -0
- data/lib/dspy_rb/runtime/channel/watchdog.rb +36 -0
- data/lib/dspy_rb/runtime/channel/writer.rb +77 -0
- data/lib/dspy_rb/runtime/channel.rb +145 -0
- data/lib/dspy_rb/runtime/child.rb +48 -0
- data/lib/dspy_rb/runtime/python.rb +43 -0
- data/lib/dspy_rb/runtime/registry.rb +48 -0
- data/lib/dspy_rb/runtime/startup.rb +53 -0
- data/lib/dspy_rb/secrets.rb +25 -0
- data/lib/dspy_rb/setup/environment.rb +120 -0
- data/lib/dspy_rb/setup/stale.rb +102 -0
- data/lib/dspy_rb/setup/uv.rb +122 -0
- data/lib/dspy_rb/signatures/signature.rb +100 -0
- data/lib/dspy_rb/signatures/types.rb +44 -0
- data/lib/dspy_rb/source.rb +64 -0
- data/lib/dspy_rb/teleprompt/bootstrap_few_shot.rb +9 -0
- data/lib/dspy_rb/teleprompt/bootstrap_few_shot_with_optuna.rb +9 -0
- data/lib/dspy_rb/teleprompt/bootstrap_few_shot_with_random_search.rb +9 -0
- data/lib/dspy_rb/teleprompt/gepa.rb +9 -0
- data/lib/dspy_rb/teleprompt/labeled_few_shot.rb +14 -0
- data/lib/dspy_rb/teleprompt/mipro_v2.rb +16 -0
- data/lib/dspy_rb/teleprompt/optimizer.rb +127 -0
- data/lib/dspy_rb/teleprompt/simba.rb +16 -0
- data/lib/dspy_rb/tool.rb +108 -0
- data/lib/dspy_rb/values/check.rb +14 -0
- data/lib/dspy_rb/values/context.rb +46 -0
- data/lib/dspy_rb/values/dataset.rb +55 -0
- data/lib/dspy_rb/values/dict.rb +17 -0
- data/lib/dspy_rb/values/env.rb +23 -0
- data/lib/dspy_rb/values/evaluation_result.rb +31 -0
- data/lib/dspy_rb/values/example.rb +134 -0
- data/lib/dspy_rb/values/fault.rb +15 -0
- data/lib/dspy_rb/values/history.rb +13 -0
- data/lib/dspy_rb/values/list.rb +16 -0
- data/lib/dspy_rb/values/literal.rb +27 -0
- data/lib/dspy_rb/values/loss.rb +12 -0
- data/lib/dspy_rb/values/optional.rb +16 -0
- data/lib/dspy_rb/values/prediction.rb +58 -0
- data/lib/dspy_rb/values/reasoning.rb +13 -0
- data/lib/dspy_rb/values/spend.rb +27 -0
- data/lib/dspy_rb/values/types.rb +164 -0
- data/lib/dspy_rb/version.rb +11 -0
- data/lib/dspy_rb/wire/departure.rb +100 -0
- data/lib/dspy_rb/wire/descriptions.rb +220 -0
- data/lib/dspy_rb/wire/facts.rb +79 -0
- data/lib/dspy_rb/wire/in_flight.rb +128 -0
- data/lib/dspy_rb/wire/json.rb +76 -0
- data/lib/dspy_rb/wire/optimizers.rb +240 -0
- data/lib/dspy_rb/wire/records.rb +44 -0
- data/lib/dspy_rb/wire/replies.rb +188 -0
- data/lib/dspy_rb/wire/requests.rb +214 -0
- data/lib/dspy_rb/wire/shape.rb +25 -0
- data/lib/dspy_rb/wire/types.rb +23 -0
- data/lib/dspy_rb/wire.rb +34 -0
- data/lib/dspy_rb.rb +191 -0
- data/lib/ruby-on-dspy.rb +4 -0
- data/python/dspy_rb/__init__.py +1 -0
- data/python/dspy_rb/__main__.py +76 -0
- data/python/dspy_rb/server/__init__.py +1 -0
- data/python/dspy_rb/server/build.py +281 -0
- data/python/dspy_rb/server/calls.py +215 -0
- data/python/dspy_rb/server/conversion.py +180 -0
- data/python/dspy_rb/server/data.py +169 -0
- data/python/dspy_rb/server/evaluation.py +107 -0
- data/python/dspy_rb/server/facts.py +357 -0
- data/python/dspy_rb/server/optimization.py +98 -0
- data/python/dspy_rb/server/pulse.py +68 -0
- data/python/dspy_rb/server/ruby.py +206 -0
- data/python/dspy_rb/server/serve.py +369 -0
- data/python/dspy_rb/server/standins.py +364 -0
- data/python/dspy_rb/server/state.py +104 -0
- data/python/dspy_rb/server/traffic.py +93 -0
- data/python/dspy_rb/values.py +51 -0
- data/python/dspy_rb/wire/__init__.py +1 -0
- data/python/dspy_rb/wire/channel.py +107 -0
- data/python/dspy_rb/wire/lines.py +269 -0
- data/python/dspy_rb/wire/shapes.py +1220 -0
- data/python/dspy_rb/wire/wire.json +4592 -0
- data/python/pyproject.toml +86 -0
- data/python/uv.lock +1576 -0
- metadata +230 -0
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module DSPyRb
|
|
4
|
+
module Execution
|
|
5
|
+
# One program call's predictor names, its predictors' spend, and its stop.
|
|
6
|
+
class Collector
|
|
7
|
+
extend Dry::Initializer
|
|
8
|
+
|
|
9
|
+
param :names, Wire::Types::Strict::Hash
|
|
10
|
+
param :parent, Wire::Types.Instance(Collector).optional, default: proc {}, reader: :private
|
|
11
|
+
option :spent, default: proc { Values::Spend.new }, reader: :private
|
|
12
|
+
option :lock, default: proc { Mutex.new }, reader: :private
|
|
13
|
+
option :stops, default: proc { [] }, reader: :private
|
|
14
|
+
|
|
15
|
+
def name(predictor)
|
|
16
|
+
names.fetch(predictor) do
|
|
17
|
+
raise Error,
|
|
18
|
+
"a #{predictor.class} called in a program's forward is not one of its predictors: hold it in " \
|
|
19
|
+
"an instance variable of the program"
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def add(spend)
|
|
24
|
+
lock.synchronize { @spent += spend }
|
|
25
|
+
|
|
26
|
+
parent&.add(spend)
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def spend
|
|
30
|
+
lock.synchronize { spent }
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def stopped
|
|
34
|
+
root.first_stop
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def stop_if_stopped
|
|
38
|
+
raise stopped if stopped
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
# Kept as its stop: every later request is refused, and the outermost call raises it though forward rescued it.
|
|
42
|
+
def hold(error)
|
|
43
|
+
root.keep(error)
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
protected
|
|
47
|
+
|
|
48
|
+
def root
|
|
49
|
+
parent ? parent.root : self
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def keep(error)
|
|
53
|
+
lock.synchronize { stops << error }
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def first_stop
|
|
57
|
+
lock.synchronize { stops.first }
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
end
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module DSPyRb
|
|
4
|
+
module Execution
|
|
5
|
+
# The Values::Context in force on this fiber, and the requests and callbacks that go by it.
|
|
6
|
+
module Context
|
|
7
|
+
KEY = :dspy_rb_context
|
|
8
|
+
|
|
9
|
+
class << self
|
|
10
|
+
def current
|
|
11
|
+
Fiber[KEY] || Values::Context::NONE
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
def within(context)
|
|
15
|
+
outer = Fiber[KEY]
|
|
16
|
+
|
|
17
|
+
Fiber[KEY] = context
|
|
18
|
+
yield
|
|
19
|
+
ensure
|
|
20
|
+
Fiber[KEY] = outer
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def capture(&block)
|
|
24
|
+
captured = current
|
|
25
|
+
|
|
26
|
+
proc { |*arguments| within(captured) { block.call(*arguments) } }
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# Asks the callback's own channel while one is served, never this process's Python, which may be another.
|
|
30
|
+
def ask(shape, serve: nil, **fields)
|
|
31
|
+
context = current
|
|
32
|
+
gates = gates(context, shape)
|
|
33
|
+
report = reporting(context, gates)
|
|
34
|
+
|
|
35
|
+
# Python asks a gated request's gates before each model call it makes.
|
|
36
|
+
fields = { **fields, gated: true } if gates
|
|
37
|
+
|
|
38
|
+
(context.callback || Runtime::Registry.current).ask(shape, report:, serve: served(serve, gates), **fields)
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
# The reply of the kind asked for, to a request that spends nothing; any other end is raised.
|
|
42
|
+
def reply(shape, kind, **)
|
|
43
|
+
exchange = ask(shape, **)
|
|
44
|
+
|
|
45
|
+
raise exchange.error unless exchange.reply.is_a?(kind)
|
|
46
|
+
|
|
47
|
+
exchange.reply
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# A callback's Ruby code runs as asked: under its callback, outside any program, in the asker's state.
|
|
51
|
+
def serving(handler, gating: false)
|
|
52
|
+
asked = current
|
|
53
|
+
storage = stored
|
|
54
|
+
|
|
55
|
+
lambda do |callback, message|
|
|
56
|
+
served = asked.serving(callback, gating, (message.in_force if message.respond_to?(:in_force)))
|
|
57
|
+
value = carried(storage) { within(served) { hooked(asked.around, gating) { handler.call(message) } } }
|
|
58
|
+
|
|
59
|
+
Values::Types.returned(value, "this #{message.kind}'s result")
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
private
|
|
64
|
+
|
|
65
|
+
# Around a gate, its refusal is raised whatever a hook rescued; around other code, a hook is plain Ruby.
|
|
66
|
+
def hooked(hooks, gating, &)
|
|
67
|
+
gating ? Around.guarded(hooks, &) : Around.run(hooks, &)
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# Listeners take a call as asked: on a thread of the gem's own, under the asker's around hooks and storage.
|
|
71
|
+
def reporting(context, gates)
|
|
72
|
+
asker = Thread.current
|
|
73
|
+
|
|
74
|
+
# A gated request's call never sent may be reported on a callback's thread; a late call's copies the storage.
|
|
75
|
+
storage = gates ? stored : {}
|
|
76
|
+
|
|
77
|
+
lambda do |call, &stop|
|
|
78
|
+
next listened(context, call, stop) if Thread.current == asker
|
|
79
|
+
|
|
80
|
+
carried(storage) { Around.run(context.around) { listened(context, call, stop) } }
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# The gates in force for a request that may call a model: its context's, else the default; nil when none.
|
|
85
|
+
def gates(context, shape)
|
|
86
|
+
return unless Wire::CALLED.include?(shape)
|
|
87
|
+
raise Error, "a gate cannot make model calls" if context.gating
|
|
88
|
+
|
|
89
|
+
gates = context.before_call.empty? ? [DSPyRb.config.before_call].compact : context.before_call
|
|
90
|
+
|
|
91
|
+
gates unless gates.empty?
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
# A gated request's gate calls go to its gates, any model call made in them refused; the rest to its Ruby code.
|
|
95
|
+
def served(serve, gates)
|
|
96
|
+
handler = serve && serving(serve)
|
|
97
|
+
|
|
98
|
+
return handler unless gates
|
|
99
|
+
|
|
100
|
+
gate = serving(asking(gates, current.collector), gating: true)
|
|
101
|
+
|
|
102
|
+
lambda do |callback, message|
|
|
103
|
+
next gate.call(callback, message) if message.is_a?(Wire::GateCall)
|
|
104
|
+
|
|
105
|
+
handler ? handler.call(callback, message) : throw(Runtime::Channel::Callback::UNSERVED)
|
|
106
|
+
end
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
# Each gate in turn, outermost first; the first to raise refuses the call, and those inside it are not asked.
|
|
110
|
+
def asking(gates, collector)
|
|
111
|
+
lambda do |message|
|
|
112
|
+
gates.each { _1.call(message.pending) }
|
|
113
|
+
|
|
114
|
+
nil
|
|
115
|
+
rescue StandardError => e
|
|
116
|
+
# Held at once, as a listener's raise is, so a later raise at the call's unsent report is not the first.
|
|
117
|
+
collector&.hold(e)
|
|
118
|
+
raise
|
|
119
|
+
end
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
# Every listener takes the call, though one raises; the first raise stops the call at once, and is raised last.
|
|
123
|
+
def listened(context, call, stop)
|
|
124
|
+
first = nil
|
|
125
|
+
|
|
126
|
+
context.on_call.each do |listener|
|
|
127
|
+
listener.call(call)
|
|
128
|
+
rescue StandardError => e
|
|
129
|
+
next if first
|
|
130
|
+
|
|
131
|
+
first = e
|
|
132
|
+
|
|
133
|
+
context.collector&.hold(e)
|
|
134
|
+
stop&.call(e)
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
raise first if first
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
# The asker's fiber storage on this thread while the block runs, and the thread's own after, whatever it set.
|
|
141
|
+
def carried(storage)
|
|
142
|
+
own = stored
|
|
143
|
+
|
|
144
|
+
begin
|
|
145
|
+
storage.each { |key, value| Fiber[key] = value }
|
|
146
|
+
|
|
147
|
+
yield
|
|
148
|
+
ensure
|
|
149
|
+
(stored.keys | own.keys).each { Fiber[_1] = own[_1] }
|
|
150
|
+
end
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
# A copy of this fiber's storage: Ruby 3.3 and later give nil for a fiber that has stored nothing.
|
|
154
|
+
def stored
|
|
155
|
+
Fiber.current.storage.to_h
|
|
156
|
+
end
|
|
157
|
+
end
|
|
158
|
+
end
|
|
159
|
+
end
|
|
160
|
+
end
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module DSPyRb
|
|
4
|
+
module Execution
|
|
5
|
+
# DSPy's Evaluate and metrics, asked from the context in force: DSPy scores, calling back Ruby's metric and program.
|
|
6
|
+
class Evaluation
|
|
7
|
+
extend Dry::Initializer
|
|
8
|
+
|
|
9
|
+
param :metric, Values::Types::Metric, reader: :private
|
|
10
|
+
|
|
11
|
+
# The Examples an evaluate scores, which its results go with in order.
|
|
12
|
+
option :devset, Values::Types::Examples, default: proc { [] }, reader: :private
|
|
13
|
+
|
|
14
|
+
# Scores `program`: a predictor Python builds from `predictor`, else a Ruby program it calls back.
|
|
15
|
+
def evaluate(program, predictor, options, overrides)
|
|
16
|
+
raise Error, "no metric: give one to Evaluate[...] or to its call" unless metric
|
|
17
|
+
|
|
18
|
+
serve = ->(message) { served(program, message) }
|
|
19
|
+
scored = predictor || Wire::RubyProgram.new(ruby: name(program))
|
|
20
|
+
fields = { program: scored, devset: sent_devset(predictor), metric: scorer.description, options:, overrides: }
|
|
21
|
+
|
|
22
|
+
Step.new(predictor && program).ask(Wire::Evaluate, Wire::Evaluated, serve:, **fields) do |reply, spend|
|
|
23
|
+
Values::EvaluationResult.new(score: reply.score, results: results(reply.results), spend:)
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# One call of one of DSPy's own metrics on an Example and a Prediction, made in Python.
|
|
28
|
+
def measure(example, prediction)
|
|
29
|
+
taken(example, Values::Example)
|
|
30
|
+
taken(prediction, Values::Prediction)
|
|
31
|
+
Values::Types.refuse_marked(prediction, "a metric's prediction")
|
|
32
|
+
fields = { metric:, example: example.wire, prediction: prediction.to_h }
|
|
33
|
+
|
|
34
|
+
Step.new.ask(Wire::Measure, Wire::Measured, **fields) { |reply, spend| score(reply.score, spend) }
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
private
|
|
38
|
+
|
|
39
|
+
# Refused by its class alone, never quoting what was given.
|
|
40
|
+
def taken(value, value_class)
|
|
41
|
+
return if value.is_a?(value_class)
|
|
42
|
+
|
|
43
|
+
raise Error, "a metric takes a DSPyRb::#{value_class.name.split("::").last}, not #{Error.class_of(value)}"
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# Each example as sent; DSPy's Evaluate calls a predictor on its inputs (dspy/evaluate/evaluate.py:174).
|
|
47
|
+
def sent_devset(predictor)
|
|
48
|
+
devset.each_with_index.map do |example, index|
|
|
49
|
+
inputs = example.input_keys ? example.inputs.to_h : {}
|
|
50
|
+
|
|
51
|
+
Values::Types.refuse_reserved(inputs, "an evaluate's example #{index}", predictor.kind) if predictor
|
|
52
|
+
example.wire
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def scorer
|
|
57
|
+
Scorer.new(metric)
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# Python's name for the Ruby program's class.
|
|
61
|
+
def name(program)
|
|
62
|
+
program.class.name&.split("::")&.last || program.class.inspect
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# The program on an example's inputs, or the metric with no trace, as Evaluate calls them (evaluate.py:174-175).
|
|
66
|
+
def served(program, message)
|
|
67
|
+
# Only a ReAct's tools are called back for the evaluate's own request.
|
|
68
|
+
return Toolbox.new(program.tools).call(message) if message.is_a?(Wire::ToolCall)
|
|
69
|
+
|
|
70
|
+
case message
|
|
71
|
+
when Wire::ProgramCall then program.call(**message.inputs)
|
|
72
|
+
when Wire::MetricCall then scorer.call(message)
|
|
73
|
+
else raise Error, "an evaluate takes no #{message.kind} callback"
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# Each example given, with the outputs and score of its result, results coming in devset order.
|
|
78
|
+
def results(given)
|
|
79
|
+
devset.zip(given).map do |example, each|
|
|
80
|
+
[example, Values::Prediction[**Values::Types.retyped(each.prediction, each.typed)], score(each.score)]
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# A Score as Ruby's value, a prediction's outputs as a Prediction with what was spent for it.
|
|
85
|
+
def score(wire, spend = Values::Spend.new)
|
|
86
|
+
wire.prediction ? Values::Prediction.of(wire.prediction, spend) : wire.value
|
|
87
|
+
end
|
|
88
|
+
end
|
|
89
|
+
end
|
|
90
|
+
end
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module DSPyRb
|
|
4
|
+
module Execution
|
|
5
|
+
# One of DSPy's optimizers, asked from the context in force: DSPy compiles the student, read back onto a copy.
|
|
6
|
+
class Optimization
|
|
7
|
+
extend Dry::Initializer
|
|
8
|
+
|
|
9
|
+
# The variable a program's detailed_results reads, a name of the gem's apart from a user's own.
|
|
10
|
+
RESULTS = :@__dspy_rb_detailed_results
|
|
11
|
+
|
|
12
|
+
# Any optimizer's options, and its compile's beside the student and trainset.
|
|
13
|
+
param :optimizer, Wire::OPTIMIZER_OPTIONS.map { Wire::Types.Instance(_1) }.reduce(:|), reader: :private
|
|
14
|
+
param :compiling, Wire::COMPILE_OPTIONS.map { Wire::Types.Instance(_1) }.reduce(:|), reader: :private
|
|
15
|
+
|
|
16
|
+
# What the options name that DSPy calls back: the metric, the teacher, and DummyLMs, whose answers Ruby keeps.
|
|
17
|
+
option :metric, Values::Types::Metric, default: proc {}, reader: :private
|
|
18
|
+
option :teacher, Wire::Types.Interface(:call).optional, default: proc {}, reader: :private
|
|
19
|
+
option :models, Wire::Types::Strict::Array, default: proc { [] }, reader: :private
|
|
20
|
+
|
|
21
|
+
# The student's Ruby source, for an optimizer that reads a Python program's: MIPROv2's proposer, SIMBA's rules.
|
|
22
|
+
option :source, Wire::Types::Strict::String.optional, default: proc {}, reader: :private
|
|
23
|
+
|
|
24
|
+
# DSPy's compile of the student's parts on the trainset's Examples, under the gates and listeners in force.
|
|
25
|
+
def compile(student, trainset)
|
|
26
|
+
program = Program.new(student)
|
|
27
|
+
serve = ->(message) { served(student.program, message) }
|
|
28
|
+
fields = { optimizer:, compiling:, student: described(program), trainset: trainset.map(&:wire) }
|
|
29
|
+
|
|
30
|
+
holding do
|
|
31
|
+
Step.new.ask(Wire::Compile, Wire::Compiled, serve:, **fields) do |reply, _|
|
|
32
|
+
detailed(program.applied(reply.state), reply.results)
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
private
|
|
38
|
+
|
|
39
|
+
# The student's description, holding its Ruby source where one is given.
|
|
40
|
+
def described(program)
|
|
41
|
+
source ? program.description.new(source:) : program.description
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
# The copy, holding GEPA's detailed results, frozen, where DSPy gave them.
|
|
45
|
+
def detailed(copy, results)
|
|
46
|
+
results ? copy.tap { _1.instance_variable_set(RESULTS, Values::Types.frozen(results)) } : copy
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# The DummyLMs held for code DSPy calls back, whose LM in force may be one of them.
|
|
50
|
+
def holding(&)
|
|
51
|
+
Context.within(Context.current.new(held: [*Context.current.held, *models]), &)
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# The program on a row's inputs, the teacher's when its callback says so; the metric; a tool; a DummyLM's answer.
|
|
55
|
+
def served(student, message)
|
|
56
|
+
case message
|
|
57
|
+
when Wire::ProgramCall then whose(message, student).call(**message.inputs)
|
|
58
|
+
when Wire::MetricCall then Scorer.new(metric).call(message)
|
|
59
|
+
when Wire::ToolCall then Toolbox.new(whose(message, student).tools).call(message)
|
|
60
|
+
when Wire::NextCall then models.find { Step.scripted?(_1) }.next_index
|
|
61
|
+
else raise Error, "a compile takes no #{message.kind} callback"
|
|
62
|
+
end
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# The teacher's program or tools when its callback says so, else the student's.
|
|
66
|
+
def whose(message, student)
|
|
67
|
+
message.teacher ? teacher : student
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
end
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module DSPyRb
|
|
4
|
+
module Execution
|
|
5
|
+
# A Ruby program as Python holds it for a compile, a save or a load: its parts described, and a state applied.
|
|
6
|
+
class Program
|
|
7
|
+
extend Dry::Initializer
|
|
8
|
+
|
|
9
|
+
# The parts of a predictor of any kind, or of a Module, as DSPy sees them.
|
|
10
|
+
param :parts, Wire::Types.Interface(:program, :walk, :marked, :module?, :rebind), reader: :private
|
|
11
|
+
|
|
12
|
+
# What Python builds: a predictor's own description, else the program's parts by path and its compiled modules.
|
|
13
|
+
def description
|
|
14
|
+
return program.predictor unless parts.module?(program)
|
|
15
|
+
|
|
16
|
+
Wire::RubyProgram.new(ruby: name, compiled: program.compiled?, **held)
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
# A copy holding each predictor's instructions and demos by name, marked compiled as DSPy marked the result.
|
|
20
|
+
def applied(state)
|
|
21
|
+
copy = parts.marked(state.compiled)
|
|
22
|
+
|
|
23
|
+
parts.module?(copy) ? module_copy(copy, state.predictors) : predictor_copy(copy, state.predictors.first)
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
# DSPy's save of its state to the JSON file at `path`; a pickle is never written.
|
|
27
|
+
def save(path, save_program:)
|
|
28
|
+
place = "#{program.class}#save"
|
|
29
|
+
|
|
30
|
+
raise Error, "#{place} saves DSPy's JSON state, never a pickle: save_program: true is refused" if save_program
|
|
31
|
+
|
|
32
|
+
Context.reply(Wire::SaveState, Wire::StateSaved, program: description, path: json_file(path, place, "writes"))
|
|
33
|
+
|
|
34
|
+
nil
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# DSPy's load of the JSON file at `path`: in place for a Module, as DSPy's load is, to a copy for a predictor.
|
|
38
|
+
def load(path)
|
|
39
|
+
file = json_file(path, "#{program.class}#load", "reads")
|
|
40
|
+
state = Context.reply(Wire::LoadState, Wire::StateLoaded, program: description, path: file).state
|
|
41
|
+
|
|
42
|
+
parts.module?(program) ? parts.rebind(replacements(state.predictors)) : applied(state)
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
private
|
|
46
|
+
|
|
47
|
+
def program
|
|
48
|
+
parts.program
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# Each predictor by the path it is held at, and each compiled module's path.
|
|
52
|
+
def held
|
|
53
|
+
first = {}.compare_by_identity
|
|
54
|
+
held = { parts: [], compiled_modules: [] }
|
|
55
|
+
|
|
56
|
+
parts.walk do |path, part|
|
|
57
|
+
if parts.module?(part)
|
|
58
|
+
held[:compiled_modules] << path if part.compiled?
|
|
59
|
+
else
|
|
60
|
+
held[:parts] << part(path, part, first)
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
held
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# Its description at the first path it is held at, which a later one names.
|
|
68
|
+
def part(path, predictor, first)
|
|
69
|
+
earlier = first[predictor]
|
|
70
|
+
|
|
71
|
+
first[predictor] ||= path
|
|
72
|
+
earlier ? Wire::Part.new(path:, same: earlier) : Wire::Part.new(path:, predictor: predictor.predictor)
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# Python's name for the program's class.
|
|
76
|
+
def name
|
|
77
|
+
program.class.name&.split("::")&.last || program.class.inspect
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
def module_copy(marked, predictors)
|
|
81
|
+
texts = predictors.filter_map { [_1.name, _1.instructions] if _1.instructions }.to_h
|
|
82
|
+
|
|
83
|
+
marked.with_instructions(texts).with_demos(predictors.to_h { [_1.name, examples(_1)] })
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# Each predictor read back, by identity, to the copy holding its state.
|
|
87
|
+
def replacements(predictors)
|
|
88
|
+
named = program.named_predictors.to_h
|
|
89
|
+
|
|
90
|
+
replaced = predictors.to_h do |state|
|
|
91
|
+
predictor = named.fetch(state.name)
|
|
92
|
+
|
|
93
|
+
[predictor, predictor_copy(predictor, state)]
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
replaced.compare_by_identity
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
def predictor_copy(marked, state)
|
|
100
|
+
copy = marked.with_demos(examples(state))
|
|
101
|
+
|
|
102
|
+
state.instructions ? copy.with_instructions(state.instructions) : copy
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
def examples(state)
|
|
106
|
+
state.demos.map { Values::Example.of(_1) }
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
# The file at `path` in full, as the wire takes it; only .json, which DSPy reads as JSON, so never a pickle.
|
|
110
|
+
def json_file(path, place, verb)
|
|
111
|
+
raise Error, "#{place} takes a path as a String, not #{Error.class_of(path)}" unless path.is_a?(::String)
|
|
112
|
+
|
|
113
|
+
file = Wire::Types::Path[path]
|
|
114
|
+
|
|
115
|
+
return file if File.extname(file) == ".json"
|
|
116
|
+
|
|
117
|
+
raise Error, "#{place} #{verb} DSPy's JSON state: the path must end in .json"
|
|
118
|
+
rescue Dry::Types::CoercionError
|
|
119
|
+
why = "it starts with a ~ that can't be expanded, or holds a null byte"
|
|
120
|
+
|
|
121
|
+
# No cause: Ruby's error quotes the path, which can hold a user's name.
|
|
122
|
+
raise Error, "#{place} can't use this path: #{why}", cause: nil
|
|
123
|
+
end
|
|
124
|
+
end
|
|
125
|
+
end
|
|
126
|
+
end
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module DSPyRb
|
|
4
|
+
module Execution
|
|
5
|
+
# The rows DSPy's own data code loads, and the orders Python's random gives, asked from the context in force.
|
|
6
|
+
class Rows
|
|
7
|
+
# A dataset's splits as a Dataset, a Hub dataset's by name, or the one list of Examples DSPy gave.
|
|
8
|
+
def load(shape, fields, call)
|
|
9
|
+
source = Wire::Departure.taken(shape, fields, call)
|
|
10
|
+
|
|
11
|
+
loaded(source, Context.reply(Wire::Load, Wire::Loaded, source:))
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
# The rows in the order Python gives their indices: one list, or a split's train and test.
|
|
15
|
+
def permute(rows, draw, **)
|
|
16
|
+
raise Error, "rows come as an Array, not #{Error.class_of(rows)}" unless rows.is_a?(::Array)
|
|
17
|
+
|
|
18
|
+
parts = Context.reply(Wire::Permute, Wire::Permuted, draw:, count: rows.size, **).parts
|
|
19
|
+
|
|
20
|
+
parts.map { |part| part.map { rows.fetch(_1) }.freeze }
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
private
|
|
24
|
+
|
|
25
|
+
def loaded(source, reply)
|
|
26
|
+
return Values::Dataset.of(reply.splits) if source.is_a?(Wire::DSPyDataset)
|
|
27
|
+
return examples(reply.examples) unless reply.splits
|
|
28
|
+
|
|
29
|
+
reply.splits.to_h { [_1.name.to_sym, examples(_1.examples)] }.freeze
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# A loader's rows, refusing a column a reader of Example would hide, which the loader's fields: leave out.
|
|
33
|
+
def examples(examples)
|
|
34
|
+
columns = examples.each_with_object({}) { |each, seen| each.record.each_key { seen[_1] = nil } }
|
|
35
|
+
|
|
36
|
+
Values::Types.shown(columns, Values::Example, "a loaded column", remedy: "leave it out with fields:")
|
|
37
|
+
examples.map { Values::Example.of(_1) }.freeze
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
end
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module DSPyRb
|
|
4
|
+
module Execution
|
|
5
|
+
# A metric as DSPy calls it: DSPy's own, built from its description, or a Ruby one, called back as DSPy passed.
|
|
6
|
+
class Scorer
|
|
7
|
+
extend Dry::Initializer
|
|
8
|
+
|
|
9
|
+
# The parameter kinds Python's stand-in takes, in the order Python takes them; a block's has no counterpart.
|
|
10
|
+
KINDS = Wire::Parameter.schema.key(:kind).type.values
|
|
11
|
+
|
|
12
|
+
# DSPy's own metric's description, or a Ruby callable.
|
|
13
|
+
param :metric, Values::Types::Metric, reader: :private
|
|
14
|
+
|
|
15
|
+
# What Python builds: DSPy's own metric, else a stand-in taking the Ruby metric's parameters, by Python's name.
|
|
16
|
+
def description
|
|
17
|
+
return metric if metric.is_a?(Wire::Metric)
|
|
18
|
+
|
|
19
|
+
Wire::RubyMetric.new(ruby: name, parameters:)
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
# The Ruby metric on as many arguments as DSPy passed, GEPA's predictor name and its trace last, None as nil.
|
|
23
|
+
def call(message)
|
|
24
|
+
example = Values::Example.of(message.example)
|
|
25
|
+
outputs = Values::Types.retyped(message.prediction, message.typed)
|
|
26
|
+
prediction = outputs && Values::Prediction[**outputs]
|
|
27
|
+
given = [example, prediction, steps(message.trace), message.pred_name, steps(message.pred_trace)]
|
|
28
|
+
|
|
29
|
+
metric.call(*given.first(message.given))
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
private
|
|
33
|
+
|
|
34
|
+
# Each step of DSPy's trace as [name, inputs, outputs].
|
|
35
|
+
def steps(trace)
|
|
36
|
+
trace&.map { [_1.predictor, _1.inputs, Values::Prediction[**_1.outputs]] }
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# Python's name for its counterpart, which DSPy names a metric's column by (dspy/evaluate/evaluate.py:190).
|
|
40
|
+
def name
|
|
41
|
+
case metric
|
|
42
|
+
when ::Method then metric.name.to_s
|
|
43
|
+
when ::Proc then "<lambda>"
|
|
44
|
+
else metric.class.name&.split("::")&.last || metric.class.inspect
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# Each as Ruby reports it, positional ones in Python's order, since DSPy passes them by place.
|
|
49
|
+
def parameters
|
|
50
|
+
reported.each_with_index.sort_by { |(kind, _), index| [KINDS.index(kind), index] }.map do |(kind, name), _|
|
|
51
|
+
Wire::Parameter.new({ kind:, name: }.compact)
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# Kinds and names, a block's left out; a proc takes any number of arguments, as a rest does.
|
|
56
|
+
def reported
|
|
57
|
+
given = callable.parameters.map { |kind, name| [kind.to_s, name&.to_s] }.select { KINDS.include?(_1.first) }
|
|
58
|
+
loose = metric.is_a?(::Proc) && !metric.lambda? && given.none? { _1.first == "rest" }
|
|
59
|
+
|
|
60
|
+
loose ? [*given, ["rest", nil]] : given
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
def callable
|
|
64
|
+
metric.is_a?(::Method) || metric.is_a?(::Proc) ? metric : metric.method(:call)
|
|
65
|
+
end
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
end
|